Invalid JSON (Unexpected token): how to find and fix the error
Trailing commas, single quotes, unclosed braces: what Unexpected token means in JSON, how to find the exact line, and how to validate from the terminal.
The API returned 400. The log says Unexpected token. The payload looks fine. You open DevTools, run JSON.parse(...) — same error. Now you're hunting for a misplaced comma in a 300-line minified string, or worse: finding out half an hour later that the JSON was never the problem, and the API was returning an HTML error page.
This post is about cutting that ritual short. The error message already tells you almost everything — the trick is knowing what each parser is trying to say, finding the exact line, and separating "badly written JSON" from "that wasn't JSON at all". If you need the format basics first, the what is JSON guide covers the grammar; here the focus is the error.
Error message → likely cause
Start by reading the message carefully, because it changes with the engine and the version. The messages below were produced by running the same broken JSON through Node 24 (the same V8 engine as Chrome), Python 3.12 and 3.13, and jq 1.7.1. The Firefox and Safari ones come from MDN's error reference and reports in the WebKit bug tracker.
| Message | Where | Likely cause |
|---|---|---|
Unexpected token '<', "<!DOCTYPE "... is not valid JSON |
Chrome, Node 20+ | The response is HTML (404, 500, login page), not JSON |
Unexpected token < in JSON at position 0 |
Older Chrome and Node (Node 18) | Same thing, old wording |
JSON Parse error: Unrecognized token '<' |
Safari | Same thing, in Safari |
"[object Object]" is not valid JSON |
Chrome, Node 20+ | JSON.parse called on an already-parsed object |
Unexpected token o in JSON at position 1 |
Older Chrome and Node | Same thing, old wording |
"undefined" is not valid JSON |
Chrome, Node 20+ | You passed undefined (empty variable, missing field) |
Unexpected end of JSON input |
Chrome, Node | Empty string or truncated JSON (204 response, cut-off download) |
Expected double-quoted property name in JSON at position 39 (line 4 column 1) |
Node 22+, current Chrome | Trailing comma before } |
Expected property name or '}' in JSON at position 4 |
Node 20+, Chrome | Single-quoted key, unquoted key, or a comment |
Expected ',' or '}' after property value in JSON |
Node 20+, Chrome | Missing comma between two properties |
Expected ',' or ']' after array element in JSON |
Node 20+, Chrome | Missing comma in an array, or ] never closed |
JSON.parse: unexpected character at line 1 column 1 of the JSON data |
Firefox | The very first character is invalid — almost always HTML |
Expecting value: line 1 column 1 (char 0) |
Python | Empty string or HTML |
Expecting property name enclosed in double quotes |
Python | Single quotes, unquoted key, or trailing comma (up to 3.12) |
Illegal trailing comma before end of object |
Python 3.13+ | Trailing comma before } |
parse error: Expected another key-value pair at line 4, column 1 |
jq |
Trailing comma before } |
Two observations that save time. First: when the problem is at the first character (position 0, line 1 column 1), the payload is probably not JSON at all — skip to the next section. Second: in V8, Unexpected token is now the minority. Recent versions describe what was expected ("Expected double-quoted property name"), which already points to the cause.
"Unexpected token < in JSON at position 0": the API returned HTML
This is the most searched JSON error and, ironically, it's almost never a JSON error. The < at position 0 is the start of <!DOCTYPE html> or <html>: the request hit a 404, a 500 with the server's error page, a proxy, or a login screen because the session expired. Your code called response.json() without looking at what came back.
const res = await fetch('/api/orders');
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
}
const type = res.headers.get('content-type') ?? '';
if (!type.includes('application/json')) {
throw new Error(`Expected JSON, got ${type}: ${(await res.text()).slice(0, 200)}`);
}
const data = await res.json();
Checking res.ok and the Content-Type before parsing turns a generic Unexpected token '<' into a message that says exactly what happened: HTTP 404: <!DOCTYPE html>.... The causes I see most, in order: wrong URL (extra slash, /api prefix missing in production), the frontend dev server returning index.html for any unknown route, an expired session redirecting to login, and the server falling into a 500 with an HTML error page.
"Unexpected token o in JSON at position 1": you parsed twice
The o at position 1 is the o in [object Object]. When you pass an object to JSON.parse, it gets converted to a string first — and String({}) is "[object Object]". Current Chrome and Node are more honest about it: "[object Object]" is not valid JSON.
const res = await fetch('/api/user');
const user = await res.json(); // already an object
JSON.parse(user); // SyntaxError: "[object Object]" is not valid JSON
The fix is to not parse again. Libraries like axios already hand you response.data as an object, so JSON.parse(response.data) hits the same error. A close cousin: "undefined" is not valid JSON, which comes from an uninitialized variable or a field that doesn't exist on the object. Oddly enough, JSON.parse(localStorage.getItem('missing-key')) doesn't throw: getItem returns null, which becomes the string "null" — valid JSON.
The syntax errors that show up constantly
When the JSON really is the problem, the grammar is small and strict (RFC 8259): no comments, no trailing commas, double quotes only, no undefined. Any deviation and the parser stops.
Trailing comma. The classic after deleting the last line of an object:
{
"name": "Rafael",
"role": "dev",
}
In Node 24: Expected double-quoted property name in JSON at position 39 (line 4 column 1). The parser points at the }, not the comma — it only finds the problem when it sees the closing brace where it expected another key. Keep that in mind: the reported position is usually just after the real mistake.
Single quotes or unquoted keys. {'name': 'Rafael'} and {name: "Rafael"} are valid JavaScript and invalid JSON. Both produce Expected property name or '}'. Common when someone copies an object from the console or from a Python print ({'a': 1} is a dict's repr, not JSON).
Missing comma. Two properties on consecutive lines with no comma produce Expected ',' or '}' after property value. Shows up when you add a field at the end of a large object.
Unclosed bracket or brace. In an array that never got its ], V8 says Expected ',' or ']' after array element and points at the line where it found the } in the wrong place. In deeply nested JSON the reported spot can be far from where the bracket was opened — formatting the document with indentation is the fastest way to see which level was left open.
undefined, NaN or comments. "debug": undefined produces Unexpected token 'u'. Use null. Comments (// or /* */) don't exist in JSON; files like tsconfig.json accept them because TypeScript reads the file as JSONC, a more permissive dialect — but the same file fed to JSON.parse breaks.
An invisible BOM. A file saved as "UTF-8 with BOM" on Windows starts with the U+FEFF character, which JSON.parse rejects with Unexpected token '' — notice the token looks empty. Strip it with text.replace(/^/, '') or save without the BOM.
How to find the exact error line
The behavior depends on the engine version, and that confuses a lot of people copying old examples. I ran the same JSON ({"a": 1,} with line breaks) on three Node versions:
Node 18: Unexpected token } in JSON at position 12
Node 20: Expected double-quoted property name in JSON at position 12
Node 22: Expected double-quoted property name in JSON at position 12 (line 3 column 1)
So from Node 22 on (and in recent Chrome) the message itself carries line and column. On older versions you only get a character offset, and converting it is trivial:
function whereItBroke(text, error) {
const m = /position (\d+)/.exec(error.message);
if (!m) return null;
const pos = Number(m[1]);
const before = text.slice(0, pos);
const line = before.split('\n').length;
const column = pos - before.lastIndexOf('\n');
return { pos, line, column, snippet: text.split('\n')[line - 1] };
}
In Python, json.JSONDecodeError already exposes lineno, colno, pos and doc (the original string), so you can print the offending line with e.doc.splitlines()[e.lineno - 1]:
import json
try:
data = json.loads(text)
except json.JSONDecodeError as e:
print(f"Line {e.lineno}, column {e.colno}: {e.msg}")
For large payloads from outside, pasting into a validator that formats and marks the line is usually faster than any script — but that's for the end of the post.
Validating JSON from the terminal
Three options, all tested:
echo '{"name": "test",}' | python3 -m json.tool
# Python 3.12: Expecting property name enclosed in double quotes: line 1 column 17 (char 16)
# Python 3.13: Illegal trailing comma before end of object: line 1 column 16 (char 15)
node -e "JSON.parse(require('fs').readFileSync('file.json', 'utf8'))"
# SyntaxError: Expected double-quoted property name in JSON at position 7 (line 1 column 8)
jq . file.json
# jq: parse error: Expected another key-value pair at line 1, column 8
Note the Python difference: up to 3.12 it points at the } (char 16); from 3.13 it has a dedicated trailing-comma message and points at the comma itself (char 15). jq gives line and column, with no surrounding snippet. In CI scripts all three exit non-zero on invalid JSON, so they work as automated checks. Most Linux distros ship Python; on macOS, python3 comes with the Xcode Command Line Tools, not out of the box.
Valid syntax is not valid data
A JSON document can parse cleanly and still be wrong for your application: a required field missing, "age": "thirty" where a number was expected. That's JSON Schema's job, not the parser's:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["name", "age"],
"properties": {
"name": { "type": "string" },
"age": { "type": "integer", "minimum": 0 }
}
}
Against this schema, {"name": "Rafael", "age": "thirty"} fails in AJV with must be integer. To test the schema before wiring it into code, the JSON Schema validator runs in the browser. Reading those messages is covered in JSON Schema type errors, the full flow in JSON schema validation, and real-project use in JSON Schema in practice.
Two traps no syntax validator catches: numbers above 2^53 - 1 lose precision in JavaScript's JSON.parse (large IDs should travel as strings), and duplicate keys are accepted by most parsers — the RFC says names "SHOULD be unique" and that behavior with duplicates is unpredictable; JSON.parse silently keeps the last value.
Frequently asked questions
What does "Unexpected token" mean in JSON?
That the parser found a character that can't appear at that point in the JSON grammar. The quoted character is the clue: < is almost always HTML instead of JSON, o at position 1 is an object parsed twice, u is undefined. In recent V8 versions many of these messages became "Expected ..." and already say what was missing.
Why doesn't JSON allow trailing commas?
Because the RFC 8259 grammar has no comma after the last element — it was kept minimal on purpose. JavaScript, JSON5 and JSONC (the dialect of tsconfig.json and VS Code settings) accept them, but JSON.parse and the standard parsers in other languages don't.
How do I fix invalid JSON automatically?
For mechanical cases (trailing commas, single quotes, unquoted keys) there are repair libraries, such as jsonrepair in JavaScript. Use them carefully: they guess intent. If the JSON came from a system you own, fix the producer; if it was truncated or was HTML, no repair helps.
What's the difference between invalid JSON and JSON that fails a schema?
Invalid JSON doesn't get past the parser — it's a syntax error and nothing works until you fix it. JSON that fails a schema parses fine but breaks the contract (wrong type, missing field). You fix the first by reading the error message; the second needs a schema and a validator like AJV.
Read the message before hunting the comma
Most JSON errors are a two-minute fix if you read the message before you start searching. Position 0 or "line 1 column 1" means it wasn't JSON: check the status and Content-Type. [object Object] is a double parse. "Expected double-quoted property name" is a trailing comma. For everything else, the position points just past the real mistake, and Node 22+, Python and jq already give you line and column. Once the syntax is fixed, the next step is the schema.
Note: the editorial content ends here. What follows is a pointer to a related tool.
Related tool
When the JSON arrives minified and too big to read, I paste it into the JSON Formatter: it formats, points to the line and column of the syntax error, and runs in the browser without sending the data anywhere.
- 01 CPU Cores vs. Threads: What Actually Changes in Practice Understand the difference between CPU cores and threads and what actually changes for performance, multitasking, gaming, and development.
- 02 MIT, Apache, and GPL Licenses: Practical Differences for Developers MIT, Apache 2.0, and GPL are not the same thing. Understand permissive vs copyleft, patent protection, and compatibility before shipping code to production.