Every JSON error, decoded: what the parser is actually telling you
TL;DR
- The decode table below covers eight common errors from
json.loadsandJSON.parse, each with its input, cause and fix. Python and Node word the same break differently, and their position numbers can point at different characters.NaNis the only input the two parsers split on at parse time (Python accepts it, Node rejects it).1e999parses to infinity in both, thenjson.dumpswritesInfinityandJSON.stringifywritesnull. Duplicate keys keep the last value in both.- Python's BOM error names its own fix (
decode using utf-8-sig). Its HTML-page error is identical to its empty-body error, so log the raw body.
If your code talks to an API, you have met Unexpected token '<', "<html><bod"... is not valid JSON. You have probably fixed it a dozen times without reading it once. This post decodes eight common errors from json.loads in Python and JSON.parse in JavaScript, plus three inputs that parse with no error at all.
Find your JSON error message and its fix
Every message below was printed by Python 3.14 or Node 24 on the input in the first column, shown without the JSONDecodeError: or SyntaxError: prefix. Older runtimes word some of these differently: older Pythons report a trailing comma in an array as Expecting value, which sends you to the wrong row.
| Input | Python says | Node says | Cause and fix |
|---|---|---|---|
| empty string | Expecting value, line 1, column 1 (pos 0) |
Unexpected end of JSON input |
Zero bytes arrived. Check the status code first. |
<html><body>Server Error</body></html> |
Expecting value, line 1, column 1 (pos 0) |
Unexpected token '<', "<html><bod"... is not valid JSON |
An error page, not JSON. Print the body, fix the request. |
{'name': 'flask'} |
Expecting property name enclosed in double quotes, line 1, column 2 (pos 1) |
Expected property name or '}' in JSON at position 1 (line 1 column 2) |
Python-dict quoting. Use json.dumps, not str(). |
{"items": [1, 2, 3,]} |
Illegal trailing comma before end of array, line 1, column 19 (pos 18) |
Unexpected token ']', ..." [1, 2, 3,]}" is not valid JSON |
A comma before the closing bracket. Delete it. |
{"msg": "hello |
Unterminated string starting at, line 1, column 9 (pos 8) |
Unterminated string in JSON at position 14 (line 1 column 15) |
The closing quote is missing. Check for a cut-off response. |
{"msg": "line1\nline2"} with a real newline |
Invalid control character at, line 1, column 15 (pos 14) |
Bad control character in string literal in JSON at position 14 (line 1 column 15) |
A literal newline inside a string. Escape it as \n. |
{"ok": true} {"ok": false} |
Extra data, line 1, column 14 (pos 13) |
Unexpected non-whitespace character after JSON at position 13 (line 1 column 14) |
Two documents back to back. Parse them one at a time. |
{} after an invisible U+FEFF |
Unexpected UTF-8 BOM (decode using utf-8-sig), line 1, column 1 (pos 0) |
Unexpected token quoting an invisible character, then is not valid JSON
|
A byte order mark leads the text. Strip it (next section). |
Positions count from 0, so you can check them against the inputs. In {"msg": "hello, Python's pos 8 is the opening quote of the string and Node's position 14 is the end of the input. In {"items": [1, 2, 3,]}, Python's pos 18 is the comma and Node names the ] after it. Match on the message wording, and use the position afterwards to find the spot.
How to fix the BOM error and tell an HTML page from an empty body
A byte order mark (BOM) is an invisible U+FEFF character at the start of the text. Python's message names the fix: decode using utf-8-sig. Open the file with encoding="utf-8-sig" and the BOM is dropped.
Node's message looks like it quotes nothing, because the quoted character is invisible. Confirm with text.charCodeAt(0) === 0xFEFF, then strip it with text.replace(/^\uFEFF/, "") before calling JSON.parse.
The HTML page is harder in Python, which prints Expecting value, line 1, column 1 (pos 0) for both an HTML page and an empty body. Node separates them: Unexpected end of JSON input for empty, and a quoted start of your input (<html><bod) for HTML. When either parser fails, log the status code and the start of the raw body before you retry.
Three inputs that parse with no error, and what breaks later
NaN is the only one where the parsers disagree at parse time. 1e999 and duplicate keys get through both, and the damage shows up later.
-
{"score": NaN}: Python returns{'score': nan}, andjson.dumpswrites it back as{"score": NaN}, which is not valid JSON. Node throwsUnexpected token 'N', "{"score": NaN}" is not valid JSON. The Python json docs say the parser acceptsNaN,Infinityand-Infinity. -
{"n": 1e999}: both parse it to infinity (infin Python, the numberInfinityin JavaScript). The serializers then diverge.json.dumpswrites{"n": Infinity}, which is not valid JSON.JSON.stringifywrites{"n":null}, which is valid JSON with the number gone. -
{"a": 1, "a": 2}: Python returns{'a': 2}, andJSON.stringifyof Node's result gives{"a":2}. The first value vanishes without a warning.
After parsing lenient input, check every number with math.isfinite (Python) or Number.isFinite (JavaScript). In Python you can also pass an object_pairs_hook that raises on a repeated key, because the hook receives every key pair. JSON.parse has no such hook, so detect duplicate keys at the source.
Paste this to name the cause in code
Both decoders match on message wording, not position, and cover five of the causes you can tell apart by wording. The raw newline is in neither list, so the last sample in each block shows the unknown fallback. Extend the lists for the other cases. MDN's JSON.parse page documents that JSON.parse throws a SyntaxError on invalid input, so try/catch is all JavaScript needs.
import json
CAUSES = [
("Expecting value", "empty body or non-JSON text, such as an HTML page"),
("Expecting property name", "single quotes around a key"),
("Unterminated string", "string never closed, was the response cut off?"),
("Extra data", "two JSON documents back to back"),
("BOM", "UTF-8 BOM, read the file with encoding utf-8-sig"),
]
def explain(text):
try:
json.loads(text)
return "parsed OK"
except json.JSONDecodeError as e:
cause = next((c for frag, c in CAUSES if frag in e.msg), "unknown, log the raw input")
return f"{cause} (pos {e.pos})"
samples = ["<html><body>Server Error</body></html>", "{'name': 'flask'}", '{"msg": "hello', "\ufeff{}", '{"msg": "line1\nline2"}']
for text in samples:
print(explain(text))
empty body or non-JSON text, such as an HTML page (pos 0)
single quotes around a key (pos 1)
string never closed, was the response cut off? (pos 8)
UTF-8 BOM, read the file with encoding utf-8-sig (pos 0)
unknown, log the raw input (pos 14)
const CAUSES = [
["Unexpected end of JSON input", "empty body"],
["Unexpected token '<'", "HTML where JSON should be"],
["Expected property name", "single quotes around a key"],
["Unterminated string", "string never closed, was the response cut off?"],
["after JSON at position", "two JSON documents back to back"],
];
function explain(text) {
if (text.charCodeAt(0) === 0xFEFF) return "UTF-8 BOM, strip it before parsing";
try {
JSON.parse(text);
return "parsed OK";
} catch (e) {
const hit = CAUSES.find(([frag]) => e.message.includes(frag));
return hit ? hit[1] : "unknown, log the raw input";
}
}
const samples = ["", "<html><body>Server Error</body></html>", "{'name': 'flask'}", '{"msg": "hello', "\uFEFF{}", '{"msg": "line1\nline2"}'];
for (const text of samples) console.log(explain(text));
empty body
HTML where JSON should be
single quotes around a key
string never closed, was the response cut off?
UTF-8 BOM, strip it before parsing
unknown, log the raw input
Next time a 200 OK hands you an HTML error page, find its row in the table and read the wording before you retry. If no row matches, the decoders print unknown, which is your cue to log the raw input.
Top comments (0)