"Unexpected token", "Expected comma" or "Invalid JSON": the messages are cryptic, but the causes are usually the same few mistakes. Paste your text into the JSON Validator and check it against this list.
1. A trailing comma
Wrong:
{"a": 1, "b": 2,}
Right:
{"a": 1, "b": 2}
JSON does not allow a comma after the last item in an object or array.
2. Single quotes
Wrong:
{'name': 'Asha'}
Right:
{"name": "Asha"}
Keys and strings must use double quotes.
3. Unquoted keys
Wrong:
{name: "Asha"}
Right:
{"name": "Asha"}
4. A missing comma
Wrong:
{"a": 1 "b": 2}
Right:
{"a": 1, "b": 2}
Every item except the last needs a comma after it.
5. Comments
JSON has no comments. Remove lines that start with // or /* ... */ before you validate.
6. Unescaped characters inside strings
A double quote or a backslash inside a string must be escaped with a backslash, and line breaks inside a string must be written as \n.
7. Wrong values
Use true, false and null in lower case. True, None or undefined are not valid JSON. Numbers cannot have leading zeros, and NaN is not allowed.
8. Mismatched brackets
Every { needs a } and every [ needs a ]. Format the text with the JSON Formatter: when the structure is indented, a missing bracket is much easier to spot.
A debugging routine
- Paste the text into the validator and read the error and its position.
- Fix that one problem, then validate again. Later errors are often hidden behind the first one.
- When it is valid, format it and check that the structure is what you expect.