All posts
May 12, 20264 min read

How to fix "Unexpected token" JSON errors

SyntaxError: Unexpected token is the most common JSON error and the least helpful. It means the parser hit a character it was not expecting, but the real mistake is often several characters earlier. The fix is knowing the five rules JSON enforces that JavaScript does not.

The five rules that break most JSON

  1. No trailing commas. {"a": 1,} is invalid. The comma after the last item is allowed in JavaScript and forbidden in JSON.
  2. Double quotes only. {'a': 1} is invalid. Both keys and string values must use double quotes.
  3. Keys must be quoted. {a: 1} is invalid, even though every JavaScript object literal writes it this way.
  4. No comments. JSON has no // or /* */. Config formats that allow comments (JSONC, JSON5) are different formats.
  5. No undefined, NaN, or Infinity. Only strings, numbers, booleans, null, objects, and arrays exist in JSON.

Find the exact character

Reading line and column numbers out of a terminal stack trace is slow. A validator that points at the failing position is faster, especially for large documents where the broken part is thousands of characters in.

Validate your JSONFormat, validate, and minify JSON with clear error messages and line numbers.

When the JSON is generated by code

If a program produced the broken JSON, do not fix the output, fix the producer. The usual culprits: string concatenation instead of a serializer, double encoding (JSON inside a JSON string), and truncation, where a log pipeline or database column cut the document off mid value. Truncation in particular always produces an unexpected end of input error, because the closing braces never arrive.

And if your “JSON” has single quotes, unquoted keys, and comments, it might actually be a JavaScript object literal or YAML. Check what format the consumer really expects before converting.