← Back to all articles

JSON Keeps Failing? Four Details That Trip Everyone

JSONPitfalls

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

  1. Read the error line/column, most parsers point right at it;
  2. Check the line above the error: a missing or extra comma is the usual root cause;
  3. Escape inner double quotes as ";
  4. 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

PartJS object literalValid JSON
Key{name: 1}{"name": 1}
String'abc'"abc"
Trailing comma[1, 2,][1, 2]
Comments// noteNot supported
Special valuesundefined, NaNOnly 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.toml or pyproject.toml.

Try it: JSON formatter