Fixing "Unexpected token" in JSON
This error means JSON.parse() hit a character it didn't expect at a specific position. The message always names the offending character and its position — that's your starting point, not a red herring.
Read the error message first
A message like Unexpected token } in JSON at position 42 tells you exactly where to look: count 42 characters into the string, or paste it into a formatter that reports line/column instead of a raw offset (Cryonel's JSON Validator does this).
The five most common causes
1. Trailing comma
{"a": 1, "b": 2,} — the comma after the last value is invalid in JSON, even though it's fine in a JavaScript object literal. This is the single most common cause of this error.
2. Single-quoted strings
{'a': 1} — JSON requires double quotes for both keys and string values. Single quotes aren't valid JSON syntax at all.
3. Unquoted keys
{a: 1} — again valid JavaScript, invalid JSON. Every key must be a double-quoted string.
4. Comments
Standard JSON has no comment syntax. // note or /* note */ anywhere in the document will break parsing.
5. A truncated response
If the error position is at (or very near) the end of the string, the JSON was likely cut off — check for a network timeout, a response size limit, or a copy-paste that missed the closing bracket.
Fix it automatically
The first four causes above can be fixed automatically — paste the broken JSON into JSON Repair and it strips comments, converts quotes, and removes trailing commas for you, then reports any error that's left (which usually means cause #5: something structural, not a syntax nit).
When the input came from an API
Inspect the HTTP status, Content-Type, and first bytes before parsing. Unexpected token < commonly means a proxy, login page, or server error returned HTML. An empty successful response can fail at position zero, while a truncated transfer fails near the end. Preserve the raw response and request ID so the server-side cause can be traced.
Do not catch the parser error and return an empty object; that converts a transport failure into misleading application state. Report the expected media type and a safe redacted preview, then fix the producer or select the correct parser. Add the smallest failing payload as a regression fixture.
Frequently Asked Questions
What does unexpected token < mean?
The body is often HTML rather than the JSON your code expected.
How do I find the reported position?
Use a validator that converts the character offset to a line and column.
Should every API response be parsed as JSON?
No. Check status, media type, and raw body first.