The Rules JSON Won't Bend On
Every rule for JSON is strict for a reason. Although some rules may appear needless and confusing, they keep JSON light weight and easily portable.
Keys must be double quoted. Single quotes and words without quotes are invalid. “Name” is valid, “name” is not.
Strings use double quotes too. Single quotes are never allowed anywhere in JSON, which trips up anyone coming from JavaScript or Python.
No trailing commas. Although your code editor may not flag it, including a comma after the last item in an object or array is illegal.
No comments. Standard JSON contains no comments. Anything resembling a comment will break the parse.
Restricted values. In standard JSON, the values of elements may be strings, numbers, booleans, null, objects. Arrays.
Break any of these and the document is invalid. That's the whole picture, and the errors below are just these rules in action.
The Most Common Errors and Their Fixes
Here are the more common errors you'll find, along with how to fix each. Together, these account for the lion's share of incorrectly formatted JSON.
Trailing comma
The number one offender. You add an item, then remove it. Leave the comma behind.
{ "a": 1, "b": 2, } That comma after `2` is invalid. The fix is to delete it. The last item in any object or array must not be followed by a comma.
Single quotes
Common when you copy from JavaScript or Python, where single quotes are fine.
{ 'name': 'Alex' } Both the key and the value use single quotes, which JSON rejects. Swap them for double quotes: `{ "name": "Alex" }`. Every string and every key needs double quotes.
Missing comma between items
Forgetting the separator between elements.
{ "a": 1 "b": 2 } There's no comma between the two pairs. Add one: `{ "a": 1, "b": 2 }`. Items in objects and arrays are split by commas.
Unquoted keys
Writing keys as bare words like you would in a JavaScript object.
{ name: "Alex" } Quotes are not needed for the key name. The key name should be written as “name”: “Alex”.
Unescaped characters in strings
A quote or backslash inside a string should also not be escaped.
{ "quote": "She said "hi"" } Early closing quotes confuse the parser. To escape a string with a quote inside it, use a backslash. “quote”: “She said "hi"" }.
How to Read a Parser Error
If your parsed JSON is incorrect, the parser will usually tell you the location of the error, sometimes literally.
A typical error reads something like "Unexpected token } in JSON at position 42" or "Expected ',' or '}' after property value." Two parts matter: the position or line number. What the parser expected versus what it found.
The position is always counted from the beginning of the string. Most of the time, the real error is one character before the position the parser indicated. “Unexpected token }” usually means there is a comma or value before the closing brace.
"Expected ',' " almost always means you forgot a comma between two items. "Unexpected string" often means two strings sit next to each other with no comma. Learn these three phrases and you'll diagnose most errors without even looking closely.
A Quick Error Reference
Three phrases will help you the most: “Unexpected token }”, “Expected ‘,’”. @CAP@“Unexpected string”.
| Parser says | Usual cause | Fix |
|---|---|---|
| Unexpected token } | Trailing comma before the brace | Remove the comma |
| Expected ',' or '}' | Missing comma between items | Add the comma |
| Unexpected string | Two values with no comma | Add a comma between them |
| Unexpected token ' | Single quotes used | Switch to double quotes |
| Unexpected end of input | Missing closing brace or bracket | Add the missing `}` or `]` |
| Bad control character | Unescaped newline or tab in a string | Escape it as `\n` or `\t` |
The problems are usually missing quotes, brackets or commas. That’s about it when it comes to errors in JSON.
A Real-World Example
Say an API call fails and your console shows "SyntaxError: Unexpected token } in JSON at position 58." You paste the payload into a validator and it highlights the problem instantly:
{
"user": "sam",
"roles": ["admin", "editor",],
"active": true
} And there it is. A comma at the end of “editor” in the array. You deleted the third element of the array and left the comma behind. Remove the comma and the JSON is valid. Position 58 put you close to the error.
This is usually the case. The error is very subtle and a validator can usually find it before you do.
How to Validate and Fix JSON Fast
Don't debug JSON by eye when you don't have to. A validator parses your text, highlights the exact line and character. Often explains the error in plain words. The free [Denwix JSON tools](here let you paste and check JSON in your browser, which beats hunting through a payload manually.
For the formal grammar, [the official JSON spec](here lays out every rule in one page. @CAP@[MDN's JSON guide](here covers parsing and common pitfalls in the browser. Both are worth a bookmark if you handle JSON regularly.
The Bottom Line
There are only a handful of things that can cause invalid JSON. Usually it’s a comma at the end of a line, a single quote, a missing comma, an unquoted key or an unescaped character. The position the parser is in and what it’s expecting to see next are key to finding the error. Unsure? Just post it to a validator and it will highlight the exact place with the error for you. The structure is strict, but because of that it’s fairly easy to find the error.
Questions and Answers
What makes JSON invalid?
JSON becomes invalid when it breaks a syntax rule. Rules can be broken by including a trailing comma, using single quotes, unquoting a key, using a missing comma. Including an unescaped character or a closing bracket. Any one of these results in the entire document being invalid.
Why does my JSON have a trailing comma error?
Since JSON doesn’t allow a comma after the last element in an array or object. So the comma should be removed.
Can JSON use single quotes?
No. JSON needs double quotes for all keys and string values. Single quotes are never valid, which often surprises people coming from JavaScript or Python.
How do I read a JSON parser error?
Look at the parser position or line and what the parser is expecting to see there. Sometimes the error occurs one character prior to the position the parser is in.
What does "Unexpected token" mean in JSON?
It means the parser encountered a character that it shouldn't expect to see there. Some possible causes are using single quotes instead of double quotes, a trailing comma or a missing comma.
Why does my JSON say "Unexpected end of input"?
You're missing a closing brace or bracket. The parser reached the end of the text and expected to find a } or ] before then. Add the closing character.
Are comments allowed in JSON?
No. In standard JSON, comments are not supported. Any text after a double forward slash or slashed comments will cause the document to be invalid. Use JSONC or another variant to include comments.
Do JSON keys need quotes?
Yes. All keys must be enclosed in double quotes. Keys that are not quoted will cause a parse error. Keys enclosed in single quotes are valid in JSON.
How do I fix "Expected ',' or '}'" in JSON?
You're missing a comma between two items. Find the spot the error points to and add a comma between the previous value and the next key or item.
Can I have a trailing comma in a JSON array?
No. Just like objects, arrays can't have a comma after the last element. Remove it. JSON5 allows trailing commas, but standard JSON does not.
Why is my JSON valid in JavaScript but not in a validator?
JavaScript object literals permit more freedom than JSON. Some validators may permise single quotes and unquoted keys. These are invalid in standard JSON as well.
How do I escape quotes inside a JSON string?
Escape inner double quotes with a backslash, like "She said "hi"". A backslash, newline, or tab should also be escaped with an extra backslash.
What value types does JSON allow?
Valid JSON values include strings, numbers, booleans (true and false), null, objects. Arrays. Functions, undefined and date objects are not valid JSON values.
Why does my JSON break with a special character?
Literally representing newlines, tabs, or control characters is not allowed in JSON. To show a newline use \n and a tab use \t.
How do I validate JSON quickly?
The JSON is most likely invalid. Pasting it in an online JSON validator is a good first step, as the tool will on its own parse the JSON, locate the error. Give a description.
What does "position" mean in a JSON error?
This is the number of characters from the start of the document to the location where the parser failed. Jump to that location to see the error.
Can a number be invalid in JSON?
Leading zeros, a trailing decimal point, NaN. @CAP@Infinity are not valid JSON numbers. Numbers must be in decimal format to be valid JSON numbers.
Why does null break my code but not the JSON?
Null is valid JSON. If your code crashes on null, that is a bug in your app. Null values should be handled explicitly on the app layer after the data is parsed.
Is empty JSON valid?
An empty object and an empty array are both valid JSON. An empty file or an empty string are also not valid JSON.
How can I prevent invalid JSON?
Use a library function to make JSON instead of creating it manually. Validate JSON manually before using it.
Why does my JSON fail with a BOM error?
Some editors will add a Byte Order Mark to the beginning of a file. Strict parsers may get confused by this character and cause the parsing to fail. Save your file as UTF-8 without a BOM to remove this character.
Can a duplicate key make JSON invalid?
The spec does not consider duplicate keys an error and allows them. Most parsers will discard all but the last key in the case of duplicates. Avoid using duplicate keys to avoid confusing bugs.
Why does my number fail to parse in JSON?
Leading zeros, trailing decimal points, NaN, Infinity, etc are not valid JSON numbers. Numbers should be in decimal format to be considered valid.
How do I validate JSON in my code?
Use your language’s built-in parser in a try-catch block. If parsing throws an exception, the JSON is invalid and the exception points to the location of the error.
What is the difference between a syntax error and a schema error?
A syntax error means the JSON isn't valid JSON at all. A schema error means the JSON is valid but doesn't match the structure your app expects.
Why is my escaped character still breaking JSON?
You may have used the wrong escape character. Backslashes in strings need to be written as double backslashes.
Can whitespace make JSON invalid?
Extra spaces, and line breaks are allowed. Are simply ignored. A control character error is raised if there is a new line within a string.
How do I pretty-print messy JSON?
Using the format function in your editor or using a JSON formatter online can re-indent the JSON making it easier to identify extraneous commas and brackets.