Why JSON.parse Throws: The Most Common Errors and How to Hunt Them Down

How to Read the Error

SyntaxError: Unexpected token } in JSON at position 5

It tells you three things at once: which token broke, at what index, and that this is syntax, not value access. Two fields matter:

  • position: the zero-based index of the failing character inside the string you passed in.
  • the token in the message: the character actually read there, e.g. }, ,, o, 1.

Position mismatches a character offset in three ways:

  • Editor columns start at 1, position starts at 0, so jumping by it lands one column off.
  • When the string carries a prefix (a log line, an HTML fragment, a BOM), every position shifts by the prefix length, and counting in the original source goes wrong.
  • After the content is re-indented, the line number for a given position changes while it still points at the same token—finding the token is more reliable than finding the line.

Four Common Error Classes

Unexpected token 'x'

JSON.parse('{"a":1,,}')   // Unexpected token ','
JSON.parse("{a:1}")       // Unexpected token 'a'   —— unquoted key
JSON.parse("{'a':1}")     // Unexpected token ' — single quotes

Three hard rules—double-quoted keys, no comments, no trailing commas—cover most of this class. When a backend returns a "JSON-like but JS-style" string, fix it at the source rather than patching around the parse call.

Unexpected end of JSON input

JSON.parse('{"a":1')          // Unexpected end of JSON input
JSON.parse('')                // same error on empty string

An empty string and a truncated payload share one message, because both mean "input exhausted". Only outside evidence separates them: whether response.text().length matches Content-Length, whether gzip decompressed. An error at the end with a length mismatch points at a proxy or gateway cutting the body, not at your missing brace.

Trailing comma

{"a":1,}   →  Unexpected token '}'
[1,2,]     →  Unexpected token ']'

JS literals permit trailing commas, so they slip into JSON naturally. The other source is tooling: some online formatters append a trailing comma, and the output fails a strict validator—pick a "strip trailing commas" option.

Unexpected token o (double parsing)

const obj = {name:'k'};
JSON.parse(obj)       // Unexpected token o in JSON at position 0  ← 'o' of [object Object]
JSON.parse('123')     // valid! yields a number, no throw

The argument must be a string. Parsing an already-parsed object stringifies it to [object Object], hence the o. That JSON.parse('123') succeeds also proves a top level may be a number—never assume the result is an object.

Three Steps: Format, Audit, Bisect

  1. Format: paste it into a JSON formatter so minified content becomes indented and the failing context is visible. The most-skipped and most effective step.
  2. Audit characters: find/replace to surface risky patterns like ,\n, {\n, [\n; check trailing commas, unquoted keys and leftover comments, and hunt the HTML or log prefix smuggled into the body—that prefix is exactly what shifts positions.
  3. Bisect: for payloads hundreds of KB+ failing near the end, parse the front and back halves separately to narrow the range, then use the byte offset to see whether a multi-byte character was cut.

Why "It Looks Right" Still Fails

  • The editor already converted it: pasting swaps curly quotes and full-width colons for half-width ones, so the screen looks fine while the bytes differ.
  • An extra serialization layer: the backend wrapped JSON.stringify twice, or the frontend stringified a string again—parsing yields a quoted string, not an object.
  • Escaping was never reversed: \uXXXX sequences were not decoded, or newlines are literal (inside JSON strings they must be \n).

Reproducible Results

Four of the most common failures, reproduced in Python (JS wording differs; positions mean the same):

import json
json.loads("{'a': 1}")        # → Expecting property name enclosed in double quotes: char 1
json.loads('{"a": 1,}')       # → Illegal trailing comma before end of object: char 7
json.loads('{"a": tru}')      # → Expecting value: char 6
json.loads('{"a": "x" "y"}')  # → Expecting ',' delimiter: char 10

Reading is uniform: the reported position is where the parser got stuck—the single quote where " was expected, the trailing comma right before }, the misspelled tru where a value should start. Convert that offset to an editor column (add 1) and most errors resolve in seconds; pasting into a JSON formatter skips the conversion entirely.

Frequently Asked Questions

What does 'Unexpected token o' from JSON.parse mean?

It almost always means you parsed an object that was already an object: JSON.parse(object) calls toString() yielding [object Object], and o is its first letter. In other words you did not pass a string at all (an actual wrongly-typed string throws 'Unexpected token "x"' where x is the offending char). Fix: confirm the argument is really a string and parse only once—double serialization creeps in easily at storage/transfer boundaries.

Why does copying JSON into a parser report 'trailing comma'?

Standard JSON disallows trailing commas: both {"a":1,} and [1,2,] throw 'Unexpected token } or ]'. JavaScript object/array literals allow them, so people used to writing JS naturally produce illegal JSON. Some online JSON formatters also append a trailing comma, causing the 'my JSON looks fine but won't parse' illusion. Fix: run a formatter with a 'strip trailing commas' option, or delete the last comma and re-validate.

The JSON from the server keeps failing in the latter half, what do I do?

Suspect truncation first: a proxy/gateway cut the body, gzip decompression failed, or the endpoint returned a timeout artifact. To tell: save the raw body and run a 'JSON validator' to see where the error points—if it always fails near the end rather than near your own field, or reports 'Unexpected end of JSON input', truncation/untermination is the likely culprit. Fix: check server logs and the Content-Length/Content-Encoding headers for completeness; during dev, print and compare response.text().length against the declared length.

The string has Chinese/emoji, why does it throw 'Unexpected end'?

It is usually a byte/encoding issue, not the content itself: ①reading with the wrong charset (e.g. declaring utf-8 on latin-1 bytes) drops bits from some sequences; ②a payload truncated right in the middle of a multi-byte char yields a broken sequence after decoding. Standard JSON is UTF-8 and Chinese/emoji may appear raw (unescaped) inside strings, so their presence alone is nothing to fix. Instead: confirm the response is received fully as UTF-8, use a JSON validator to find the exact byte offset, and look backward to see which multi-byte character was cut.

← Back to Blog