Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading