// A function that trims any characters beyond a JSON string in a given text
function trimJson(text) {
// Initialize a flag to indicate if the parsing is successful
let parsed = false;
// Initialize a variable to store the trimmed text
let trimmed = text;
// Loop until the parsing is successful or the text is empty
while (!parsed && trimmed.length > 0) {
// Try to parse the trimmed text as JSON
try {
const json = JSON.parse(trimmed);
// If successful, set the flag to true
parsed = true;
} catch (error) {
// If not, check the error message
const message = error.message;
// If the error message contains "Unexpected token", it means there are extra characters before the JSON string
if (message.includes("Unexpected token")) {
// Find the unexpected token and its position
const token = message.match(/Unexpected token '(.*)'/)[1];
const position = trimmed.indexOf(token);
// Slice the text from that position to the end
trimmed = trimmed.slice(position);
}
// If the error message contains "Unexpected non-whitespace character", it means there are extra characters after the JSON string
else if (message.includes("Unexpected non-whitespace character")) {
// Find the position of the unexpected character
const position = message.match(/at position (\d+)/)[1];
// Slice the text up to that position
trimmed = trimmed.slice(0, position);
}
// Otherwise, return an empty string
else {
return '';
}
}
}
// Return the trimmed text
return trimmed;
}
// A valid JSON string
const text1 = '{"foo":"bar"}';
console.log(trimJson(text1)); //=> '{"foo":"bar"}'
// A JSON string with extra characters at the end
const text2 = '{"foo":"bar"} xyz';
console.log(trimJson(text2)); //=> '{"foo":"bar"}'
// A JSON string with extra characters at the beginning and the end
const text3 = 'abc {"foo":"bar"}...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.