DEV Community

Avinash Verma
Avinash Verma

Posted on

Fixing broken JSON: why "Unexpected token" usually isn't a JSON problem

You call JSON.parse() (or res.json()) and get:

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Before you hunt for a missing comma — most of these errors aren't broken JSON at all.

"Unexpected token <" → you got HTML, not JSON

The #1 cause, and it has nothing to do with your JSON. The server returned an HTML page (a 404, a login redirect, a Cloudflare challenge) and your code parsed it as JSON.

const res = await fetch(url);
const text = await res.text();
console.log(text.slice(0, 200)); // <!DOCTYPE html>... there is your answer
Enter fullscreen mode Exit fullscreen mode

Now it's a request problem (wrong URL, missing auth, expired token) — fix the request, not the parser.

"Unexpected token o at position 1" → you double-parsed

The o is from [object Object]. You parsed something already parsed — fetch().then(r => r.json()) parses for you. Don't do it twice.

Actually-broken JSON

When it is malformed, it's almost always: trailing commas ({"a":1,}), single quotes, unquoted keys ({a:1}), comments (JSON has none), Python values (True/None), or missing brackets from a truncated copy-paste.

Fix it fast

Find the exact line with a validator; auto-fix the lenient cases with JSON5.parse() or a repair tool. For a quick browser fix I use https://jsonviewertool.com/json-repair (rewrites trailing commas, single quotes, unquoted keys to strict JSON) and https://jsonviewertool.com/json-validator to pinpoint the error line — both client-side.

10-second triage

  • Mentions < → HTML, not JSON. Fix the request.
  • Mentions o at position 1 → you double-parsed.
  • Anything else → malformed → validate + repair.

Top comments (0)