The 5 Mistakes That Break JSON (and How to Fix Them Fast)
Quick answer: almost every "invalid JSON" error comes from five habits carried over from JavaScript. JSON is stricter than JS: keys and strings need double quotes, there is no trailing comma, and there are no comments.
Quick answer: almost every "invalid JSON" error comes from five habits carried over from JavaScript. JSON is stricter than JS: keys and strings need double quotes, there is no trailing comma, and there are no comments.
The five mistakes
| Mistake | Broken | Fixed |
|---|---|---|
| Single quotes | {'name': 'Ali'} |
{"name": "Ali"} |
| Trailing comma | {"a": 1,} |
{"a": 1} |
| Unquoted key | {name: "Ali"} |
{"name": "Ali"} |
| Comments | {"a": 1 // note} |
remove the comment |
| Missing bracket | {"a": [1, 2} |
{"a": [1, 2]} |
Find the exact error in code
JSON.parse tells you roughly where it failed:
function checkJson(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (e) {
return { ok: false, error: e.message }; // e.g. "Unexpected token } in JSON at position 17"
}
}
checkJson('{"a": 1,}'); // { ok: false, error: "..." }
The position in the message is a character offset. Count to it, or paste the text into a formatter, to see the line.
Pretty print or minify
const pretty = JSON.stringify(value, null, 2); // readable, 2 spaces
const small = JSON.stringify(value); // minified, one line
Pretty printing is for people. Minified JSON is smaller to send.
Two gotchas
-
undefined, functions andNaNare not valid JSON values.JSON.stringifydropsundefinedand functions from objects and turnsNaNintonull. - Big numbers lose precision in JavaScript because they are 64-bit floats. If an ID has more than 15 digits, send it as a string.
A free tool for it
If you just need to paste and check, I keep a free browser-based JSON formatter and validator. It formats, minifies and shows the error, and nothing is uploaded. I also wrote a plain guide with the same table: How to format JSON online and fix common errors.
Originally published at saveanyreel.com.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.