DEV Community

Cover image for "7 Reasons Your JSON Is Invalid (and How to Fix Each One)." published: false
Abdul Muqeet
Abdul Muqeet

Posted on

"7 Reasons Your JSON Is Invalid (and How to Fix Each One)." published: false

#ai

"The same few mistakes cause most JSON.parse errors. Here are seven of them, with a before and after for each, and a quick way to find the problem."

Tags: json, webdev, beginners, tutorial

You paste a JSON response into your code, JSON.parse throws, and the error points at a spot that looks perfectly fine. Most of the time the cause is one of a handful of mistakes that come up again and again.

Here are seven of them, each with a before and after.

1. A trailing comma

{ "name": "Ali", "age": 25, }
Enter fullscreen mode Exit fullscreen mode

Remove the last comma:

{ "name": "Ali", "age": 25 }
Enter fullscreen mode Exit fullscreen mode

JavaScript object literals and many other languages allow a trailing comma. JSON does not, which is why code that looks fine in your editor fails when it is parsed as JSON.

2. Single quotes

{ 'name': 'Ali' }
Enter fullscreen mode Exit fullscreen mode

JSON only accepts double quotes for both keys and string values:

{ "name": "Ali" }
Enter fullscreen mode Exit fullscreen mode

3. Keys without quotes

{ name: "Ali" }
Enter fullscreen mode Exit fullscreen mode

This is valid JavaScript, but not valid JSON. Every key needs double quotes:

{ "name": "Ali" }
Enter fullscreen mode Exit fullscreen mode

4. Comments

{
  // the user's name
  "name": "Ali"
}
Enter fullscreen mode Exit fullscreen mode

JSON has no comment syntax, so both // and /* */ cause an error. Remove them. Some tools, such as the settings file in VS Code, accept comments, but that is the tool being lenient, not JSON itself. If you control the format and need notes, a key such as "_comment" works.

5. undefined, NaN and Infinity

{ "score": undefined, "ratio": NaN }
Enter fullscreen mode Exit fullscreen mode

None of these exist in JSON. Use null, or leave the key out:

{ "score": null, "ratio": null }
Enter fullscreen mode Exit fullscreen mode

If you build your JSON with JSON.stringify, you will not see this one often, because it drops undefined values and turns NaN and Infinity into null. The problem usually shows up when the JSON is written by hand or put together by joining strings.

6. Characters that need escaping

{ "path": "C:\Users\ali" }
Enter fullscreen mode Exit fullscreen mode

A backslash starts an escape sequence, and \U is not a valid one. Double the backslashes:

{ "path": "C:\\Users\\ali" }
Enter fullscreen mode Exit fullscreen mode

The same goes for line breaks. A real line break inside a string is not allowed. Write \n instead.

7. Numbers written the way you would in code

{ "id": 007, "bonus": +5, "rate": .5, "mask": 0xFF }
Enter fullscreen mode Exit fullscreen mode

JSON numbers are stricter than JavaScript numbers. No leading zeros, no plus sign, no bare decimal point, no hex:

{ "id": 7, "bonus": 5, "rate": 0.5, "mask": 255 }
Enter fullscreen mode Exit fullscreen mode

One more thing worth knowing: a number above 9007199254740991 loses precision when JavaScript parses it. If you send large IDs, send them as strings.

Finding the problem quickly

Wrap the parse in a try/catch and log the message:

try {
  JSON.parse(text);
} catch (err) {
  console.log(err.message);
}
Enter fullscreen mode Exit fullscreen mode

The wording of the message differs between browsers and engines. Some give a line and column; others only a character position. When the message does not help, paste the JSON into a formatter. If it is valid, the formatter indents it so you can read the structure. If it is not, you get the error straight away.

I run a small site of free browser tools, and one of them is a JSON formatter. It formats, minifies, and checks JSON, and it runs entirely in your browser, so nothing you paste is uploaded. Any formatter will do the same job, so use whichever you like.

The habit that prevents most of this

If your code produces the JSON, let a library do it. JSON.stringify in JavaScript, json.dumps in Python, and their equivalents handle quotes, escaping, and commas for you. Most invalid JSON comes from people building the string by hand.

Top comments (0)