DEV Community

Sanjaya Sahu
Sanjaya Sahu

Posted on

Why JSON.parse Says Unexpected Token: 8 Causes and Fixes

"Unexpected token" is the most useless error message in web development. It tells you something is wrong with your JSON but not what. Here are the causes I run into most, in the order I check them.

1. Trailing commas

{"a": 1,} is valid JavaScript but invalid JSON. Remove the last comma.

2. Single quotes

JSON requires double quotes for both keys and strings. {'a': 1} fails.

3. Unquoted keys

{a: 1} is a JavaScript object literal, not JSON.

4. Comments

JSON has no comments. Strip // and /* */ before parsing, or use JSONC or JSON5 where the tool supports it.

5. An HTML error page instead of JSON

Unexpected token < in JSON at position 0 almost always means the server returned HTML (a 404 or 500 page). Check response.ok and the Content-Type header before calling response.json().

6. BOM or invisible characters

A byte order mark at the start of a file breaks some parsers. Re-save as UTF-8 without BOM.

7. NaN, undefined and Infinity

None of these exist in JSON. JSON.stringify turns them into null or drops the key, so round trips silently change your data.

8. Big numbers

JavaScript numbers lose precision past 2^53. IDs from other systems should travel as strings.

Find the exact line

Paste the payload into a validator that points at the failing line and column, instead of squinting at a minified blob. I made one that runs entirely in your browser, so nothing is uploaded.

Try it: JSON Validator

Related: JSON Formatter, JSON Diff and JSON to TypeScript. All 590+ tools at webdevtoolbox.com run client-side.

Top comments (0)