JSON is not a JS object literal
JSON is a data interchange format and far stricter than JavaScript object literals: keys must be double-quoted, strings must use double quotes, no comments, and no trailing commas. Many errors come from pasting JS syntax straight into JSON.
The usual suspects
- Trailing comma:
[1, 2, 3,]; - Single quotes:
{'name': 1}should be double-quoted; - Unquoted keys:
{name: 1}must be"name"; - Comments: neither
//nor/* */is valid.
A fast debugging routine
- Read the error line/column, most parsers point right at it;
- Check the line above the error: a missing or extra comma is the usual root cause;
- Escape inner double quotes as
"; - When unsure, format first, clean indentation makes problems obvious.
Formatting and minifying
Format with 2-space indentation while developing, minify for transport. JSON containing sensitive data is best processed with a local tool instead of untrusted online services.
Valid vs invalid at a glance
| Part | JS object literal | Valid JSON |
|---|---|---|
| Key | {name: 1} | {"name": 1} |
| String | 'abc' | "abc" |
| Trailing comma | [1, 2,] | [1, 2] |
| Comments | // note | Not supported |
| Special values | undefined, NaN | Only null |
Code example: parse safely
// Never parse untrusted input without error handling
function safeParse(text) {
try {
return { ok: true, data: JSON.parse(text) };
} catch (e) {
// e.message usually carries a position hint
return { ok: false, error: e.message };
}
}
// Validate and format from the command line (jq)
// jq . data.json -> validate and pretty-print
// jq -c . data.json -> minify to a single line
JSON vs YAML vs TOML
- JSON: the de facto interchange standard, no comments, no multiline strings; ideal for APIs and generated config;
- YAML: readable with comments, good for hand-edited config, but indentation-sensitive with implicit typing traps;
- TOML: explicit and unambiguous, a good fit for project files such as
Cargo.tomlorpyproject.toml.
Try it: JSON formatter