Home > Blockchain >  Is there a more advanced JSON parser than the one in vanila js?
Is there a more advanced JSON parser than the one in vanila js?

Time:08-04

I have a program that checks if JSON is correctly formatted but right now I can't get the errors right.

I use JSON.parse() to parse the json passed in, inside of a try/catch statement, then I take the error (if generated), and make a error message of my own. However, the error logged tells me that I have a error at position x, but I don't understand what the position is. I want to output an error that tells the user on which line and which column the error happened in the json. I have read that my current method cannot give me the line and column, but is there any way to do it, or is there an external library that can do this?

(Its just js, not ts or node)

CodePudding user response:

The position is the index in the string at which the (first) unexpected character was found. For example

JSON.parse(`{"foo":bar`)

produces

Uncaught SyntaxError: Unexpected token b in JSON at position 7

because index 7 is

{"foo":bar
       ^

If that isn't enough for you, and you have newlines in the string as well, then it's trivial to identify the number of newlines before the error position - just slice the string from 0 to the position, then split by \n to find out the number of lines, and look at the number of characters in the last split string to find out the number of rows.

const badJSON = `
{
  "foo"
  :
    'bar`;
try {
  JSON.parse(badJSON);
} catch(e) {
  const position = e.message.match(/\d /)[0];
  const textToPosition = badJSON.slice(0, position);
  const splits = textToPosition.split('\n');
  const lines = splits.length;
  const columns = splits[lines - 1].length;
  console.log('Error at', lines, columns);
}

  • Related