flashman
← All posts

JSON parse error unexpected token? Find the bad byte fast

Debug JSON unexpected token errors by checking line numbers, invisible bytes, quotes, trailing commas, and API response content before changing code safely.

2026-06-23 · 6 min read · Rahul Chitturi

  • json
  • api
  • debugging

Unexpected token errors feel vague because the parser only knows where JSON stopped making sense. The real cause may be one character earlier, a copied response wrapper, or an HTML error page returned by a proxy instead of the JSON you expected.

Before rewriting fetch logic, isolate the exact payload and validate it as data. Most fixes come from comparing what the server actually returned with what the client thought it requested.

Confirm the response is JSON

A 200 status does not guarantee a JSON body. Load balancers, auth middleware, and framework error pages can return HTML, plain text, or an empty body while the client still calls JSON.parse. Check content-type, status code, and the first non-whitespace character before blaming the parser.

  • HTML usually starts with < or <!doctype
  • Empty responses break code that always expects an object
  • Text error bodies may contain stack traces or gateway messages
  • Compressed or encoded payloads need to be decoded before parsing

Use the line and column carefully

Line and column numbers point to where parsing failed, not always where the typo started. A missing quote can make a later colon look wrong. A trailing comma can make the next closing brace look suspicious. Format a copy of the payload and inspect the surrounding object.

If the payload is minified, pretty-printing gives you structure. If it cannot be pretty-printed, validate the smallest copied section that still fails.

Look for invisible input drift

JSON allows whitespace, but not every invisible character belongs in every position. Byte order marks, smart quotes, copied non-breaking spaces, and control characters from logs can turn valid-looking examples into broken input.

  • Replace smart quotes with plain double quotes
  • Remove trailing commas after the final array or object item
  • Avoid comments in strict JSON payloads
  • Compare a working sample with the failing one after redaction

A Flashman workflow

Paste a redacted copy into the JSON formatter first. If it fails, use the reported position to narrow the area, then diff the broken payload against a known-good response. When configuration started as YAML, convert it to JSON to catch structural mismatches before shipping it.

Flashman runs these checks in your browser, which is useful when API responses include internal IDs or tenant-specific fields. Redact secrets, validate the exact bytes you received, and keep the failing fixture for a regression test.

Try these tools