SyntaxError: JSON.parse: bad parsing

Posted by Deeksha Agarwal | April 5, 2018
Debug β€’ Miscellaneous β€’

8883 Views | 3 Min Read

SyntaxError: JSON.parse: bad parsing

JSON or JavaScript Object Notation is a ubiquitous data format used by all sorts of mobile and web apps for asynchronous browser-server communication. JSON is an extremely popular data format, very easy to work with, compatible with every major programming language, and is supported by every major browser. However just like any programming language, it throws a lot of errors when it decide that today is not going to be your day.

JSON.Parse Syntax Errors

In most web applications, nearly all data transferred from web server is transmitted in a string format. To convert that string into JSON, we use JSON.parse() function, and this the main function that throws errors. Nearly all JSON.parse errors are a subset of SyntaxError error type. Debugging console throws around 32 different errors messages when you mess up your JSON data. And some of them are very tricky to debug; and yes I am talking about you unexpected non-whitespace character after JSON data.

Why the SyntaxError Horror?

SyntaxError is an inherited object of the main error object The main reason behind the error is usually a mistake in the JSON file syntax. You mess up and put a β€œ instead of a β€˜ and you invite to face the SyntaxError JSON.parse: unexpected character.

Just like every programming language, a JSON file has a fixed syntax. Small syntax errors throws errors. For example, in the following code, i forgot to remove a trailing comma

Error1

Similarly, in this example I forgot to add }

error2

How to Catch The Error Before Hand?

The problem with debugging JSON errors are that you get to know about one error at a time. Debuggers throw the first error they find and then stop. It would be upto you to regression find the bugs. Usually it’s not as difficult as it sounds.

The first step is to make sure that your JSON file is perfect from the get go. Here you can take help from JSON linting tools like cleverly named jsonlint.com

If you don’t have any control over the receiving JSON file, then the next step is to add catch exceptions around your JSON.parse.

Also, here are the main errors related to JSON.parse that I very painstakingly collected from a very single source [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse] πŸ˜›

If this doesn’t help, then you are in for one long debugging session. Leave a comment below with your issue. I can help.

Written by Deeksha Agarwal

Related Articles

Top 13 Skills Of A Proficient QA Manager In 2019

Top 13 Skills Of A Proficient QA Manager In 2019

170679 Views | 13 Min Min Read

Leave a Reply

Your email address will not be published. Required fields are marked *