What the exception actually carries
json.JSONDecodeError is a subclass of ValueError with four useful attributes, and most code catches the exception without ever reading them. The message you see in the traceback is e.msg concatenated with a position, which is why the parts separate cleanly once you ask for them separately.
>>> import json
>>> try:
... json.loads('{"a": 1,}')
... except json.JSONDecodeError as e:
... print(repr(e.msg), e.lineno, e.colno, e.pos)
'Illegal trailing comma before end of object' 1 8 7The three numbers are the same place described twice. pos is a zero-based offset into the whole document, colno is the one-based column, and lineno counts newlines. That is why the message reads char 7 and column 8 for the same character — an off-by-one that looks like a bug and is just two conventions in one sentence.
e.doc holds the original document. e.pos indexes it, so e.doc[max(0, e.pos - 20):e.pos + 20] gives you the twenty characters on either side of the failure without printing a megabyte into your logs. That one line is more useful than the message itself.
One message, four unrelated problems
The most searched form of this error is the position-zero form, and the reason it is hard to act on is that Python reports it for four completely different situations. The same four inputs handed to V8 produce four different sentences, which shows how much information the Python message discards.
| What actually arrived | V8 says |
|---|---|
Empty response body | Unexpected end of JSON input |
Whole document wrapped in quotes'{"a":1}' | Unexpected token ''', "'{"a":1}'" is not valid JSON |
HTML page<!DOCTYPE html><html></html> | Unexpected token '<', "<!DOCTYPE "... is not valid JSON |
JSON inside an assignmentconst cfg = {"a":1}; | Unexpected token 'c', "const cfg = {"a":1};" is not valid JSON |
Read the V8 column and the diagnosis writes itself. An angle bracket means the response was a web page. A lowercase c means someone copied a statement out of source code. A single quote means the value went through repr() at some point. Nothing at all means the body was empty. Python's message collapses all four into char 0, so the first character is the only evidence you have left — print it before you touch anything else.
body = response.content
print(repr(body[:40])) # b'' or b'<!DOCTYPE html>' or b"'{..."
# Only then parse. The first forty bytes answer the question
# that the exception message refused to.Older messages still showing up in search
Search results still send people to this page with messages that current CPython no longer prints. They come from Python 2, older simplejson releases and libraries that wrap the decoder. The cause is the same as the modern position-zero error: the parser never found a value at the start of the document.
| Message you searched for | Current equivalent | What to check first |
|---|---|---|
| No JSON object could be decoded | Expecting value: line 1 column 1 (char 0) | Print repr(body[:40]). Empty body, HTML and a quoted string all arrive here. |
| Extra data | Extra data: line 1 column 8 (char 7) | One document was expected, but two were concatenated or a suffix was appended after the closing brace. |
| the document is empty (offset: 0) | Expecting value: line 1 column 1 (char 0) | The response body had zero length. Check the status code and the proxy before looking at the JSON. |
| Parse error / JSON parse error | Varies by engine and position | This is a category, not a message. Paste the exact sentence and the first forty bytes into the validator to get a position. |
If the message you have is not in either table, it is still worth checking the first byte before the syntax. A decoder that reports position zero has not read far enough to know which document you meant.
The one message that changed between releases
Fourteen malformed documents were run through four interpreters. Exactly one message moved. A trailing comma is reported as a missing property name on 3.9, 3.10 and 3.12, and as a trailing comma on 3.13 — and the column moved from 9 to 8 along with it.
| CPython | Message | Position |
|---|---|---|
| 3.9.6 | Expecting property name enclosed in double quotes | line 1 column 9 (char 8) |
| 3.10.8 | Expecting property name enclosed in double quotes | line 1 column 9 (char 8) |
| 3.12.14 | Expecting property name enclosed in double quotes | line 1 column 9 (char 8) |
| 3.13.12 | Illegal trailing comma before end of object | line 1 column 8 (char 7) |
This matters for a practical reason. Most explanations of this error were written before 3.13 and quote the old sentence, so someone on 3.13 who searches for Illegal trailing comma before end of object finds nothing that matches their traceback, while everyone else finds pages describing a message their interpreter no longer produces. Both readers end up at the trailing comma guide eventually, but only after concluding that their version is broken.
The other thirteen inputs returned identical messages on all four versions, which is worth knowing too: the instability is narrow and recent, not a general property of the module.
Every message, measured
The table below is the whole set, produced by running each input through 3.13.12 rather than by quoting documentation. The V8 column is there because the contrast is the fastest way to work out which of the two parsers is complaining about what.
| Input | Python | V8 |
|---|---|---|
{'a': 1}Single quotes around a key | Expecting property name enclosed in double quotesline 1 column 2 (char 1) | Expected property name or '}' in JSON at position 1 (line 1 column 2) |
{"a": 1,}Trailing comma | Illegal trailing comma before end of objectline 1 column 8 (char 7) | Expected double-quoted property name in JSON at position 8 (line 1 column 9) |
{a: 1}Unquoted key | Expecting property name enclosed in double quotesline 1 column 2 (char 1) | Expected property name or '}' in JSON at position 1 (line 1 column 2) |
{"a": True, "b": None}Python literals True / None | Expecting valueline 1 column 7 (char 6) | Unexpected token 'T', "{"a": True, "b":"... is not valid JSON |
{"a": NaN}NaN literal | No error, parsed | Unexpected token 'N', "{"a": NaN}" is not valid JSON |
{"a": 1} // noteComment after the document | Extra dataline 1 column 10 (char 9) | Unexpected non-whitespace character after JSON at position 9 (line 1 column 10) |
Empty response body | Expecting valueline 1 column 1 (char 0) | Unexpected end of JSON input |
{"a":1}{"b":2}Two documents concatenated | Extra dataline 1 column 8 (char 7) | Unexpected non-whitespace character after JSON at position 7 (line 1 column 8) |
<U+FEFF>{"a":1}Byte-order mark kept in the string | Unexpected UTF-8 BOM (decode using utf-8-sig)line 1 column 1 (char 0) | Unexpected token '', "{"a":1}" is not valid JSON |
{"a": "line\nbreak"} with a real line breakLiteral newline inside a string | Invalid control character atline 1 column 12 (char 11) | Bad control character in string literal in JSON at position 11 (line 1 column 12) |
{"a": 01}Leading zero in a number | Expecting ',' delimiterline 1 column 8 (char 7) | Unexpected number in JSON at position 7 (line 1 column 8) |
'{"a":1}'Whole document wrapped in quotes | Expecting valueline 1 column 1 (char 0) | Unexpected token ''', "'{"a":1}'" is not valid JSON |
<!DOCTYPE html><html></html>HTML page | Expecting valueline 1 column 1 (char 0) | Unexpected token '<', "<!DOCTYPE "... is not valid JSON |
const cfg = {"a":1};JSON inside an assignment | Expecting valueline 1 column 1 (char 0) | Unexpected token 'c', "const cfg = {"a":1};" is not valid JSON |
One row deserves a second look: NaN is not rejected. Python parses it and hands back float('nan'), while V8 refuses the same bytes. If a payload survives your Python service and fails in the browser that consumes it, this is one of the reasons, and there is a wider table of engine disagreements for the rest.
Whether you read bytes or text decides the BOM
The single most common reason for a file that parses on one machine and not on another is that one code path opens it in binary mode and the other in text mode. The bytes are identical; the argument type is not, and Python takes a different branch for each.
| How it was read | Result |
|---|---|
UTF-8 file with a BOM, read as bytesjson.loads(open(path, 'rb').read()) | acceptedBytes are decoded with BOM detection, so the BOM is removed before parsing starts. |
The same file, read as textjson.loads(open(path, encoding='utf-8').read()) | rejectedThe BOM survives as U+FEFF, which is not whitespace and not a value. |
A UTF-16 encoded document, read as bytesjson.loads('{"a":1}'.encode('utf-16')) | acceptedThe BOM in the first bytes is enough for Python to pick the UTF-16 codec. |
Latin-1 bytesjson.loads(b'{"name": "caf\xe9"}') | UnicodeDecodeErrorNot a JSON error at all, so `except json.JSONDecodeError` does not catch it. |
The third row surprises people: bytes encoded as UTF-16 parse correctly, because the BOM in the first two bytes tells Python which codec to use. The fourth row matters more than it looks. A Latin-1 byte raises UnicodeDecodeError, not JSONDecodeError, and the two share no ancestor below Exception — so the handler everyone writes will miss it.
try:
data = json.loads(raw)
except UnicodeDecodeError:
... # not JSON at all: the bytes are not UTF-8
except json.JSONDecodeError as e:
... # a real syntax error, and e.pos points at itWhat it accepts when you expected a failure
Three behaviours catch people out in the other direction, because the parser is more permissive than the specification they read:
NaN,Infinityand-Infinityparse by default. The strictness switch isparse_constant, not a flag, so there is no simple “strict mode” to turn on.- Duplicate keys are accepted and the last one wins.
{"a": 1, "a": 2}returns a dict with one key, no warning, no error — which silently destroys data whenever a document was built by concatenating two objects. - Text after the first document is an error only if it is not whitespace. That is why a trailing newline is fine and a trailing comment is
Extra data.
The pattern to take away is that a successful json.loads proves the bytes parsed. It does not prove the document was the one you meant — no parser can tell you that two members shared a name.
The fastest way to the real error
The message describes the parser's state, so treat the position as a hint and the surrounding text as evidence. Four steps, in order, resolve almost every occurrence of this error:
- Print the first forty bytes of the body. If the input is empty or starts with
<, the parse never had a chance and the bug is in the HTTP layer, not in the data. - Print the twenty characters around
e.posfrome.doc. A single quote, a comment, or a capitalisedTrueis visible immediately and tells you where the document was produced. - Paste it into a validator that shows the failing offset in the text rather than only the message, so you can see the character and its neighbours at the same time.
- If the document is large, compare it against a known-good sample with a structural diff instead of reading it. One comma is easier to find as a difference than as a line in a traceback.
One related message is worth knowing by sight: Unexpected end of JSON input is the V8 sentence for the empty-body case, and it has its own guide covering which truncations produce it — only three of six do.