trimJson

Bing AI

by Abhishek Kumar

JavaScript

// 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"}...