Skip to content
DevTinyTools

Errors

JSON decode error: what each message means

Python reports this error for an empty body, for a web page, and for a document that is correct except for one comma — and the sentence is identical all three times. What separates them is the first byte, not the wording.

9 min readTool: JSON Validator

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 7

The 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.

Four inputs that all report line 1 column 1 char 0 in Python, next to what V8 says about each
What actually arrivedV8 says
Empty response bodyUnexpected 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.

Legacy JSON decode messages and what they mean in current Python
Message you searched forCurrent equivalentWhat to check first
No JSON object could be decodedExpecting value: line 1 column 1 (char 0)Print repr(body[:40]). Empty body, HTML and a quoted string all arrive here.
Extra dataExtra 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 errorVaries by engine and positionThis 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.

The same trailing comma input reported by four CPython versions
CPythonMessagePosition
3.9.6Expecting property name enclosed in double quotesline 1 column 9 (char 8)
3.10.8Expecting property name enclosed in double quotesline 1 column 9 (char 8)
3.12.14Expecting property name enclosed in double quotesline 1 column 9 (char 8)
3.13.12Illegal trailing comma before end of objectline 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.

Fourteen malformed inputs and the exact message each parser returns
InputPythonV8
{'a': 1}Single quotes around a keyExpecting 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 commaIllegal 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 keyExpecting 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 / NoneExpecting valueline 1 column 7 (char 6)Unexpected token 'T', "{"a": True, "b":"... is not valid JSON
{"a": NaN}NaN literalNo error, parsedUnexpected token 'N', "{"a": NaN}" is not valid JSON
{"a": 1} // noteComment after the documentExtra dataline 1 column 10 (char 9)Unexpected non-whitespace character after JSON at position 9 (line 1 column 10)
Empty response bodyExpecting valueline 1 column 1 (char 0)Unexpected end of JSON input
{"a":1}{"b":2}Two documents concatenatedExtra 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 stringUnexpected 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 stringInvalid 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 numberExpecting ',' delimiterline 1 column 8 (char 7)Unexpected number in JSON at position 7 (line 1 column 8)
'{"a":1}'Whole document wrapped in quotesExpecting valueline 1 column 1 (char 0)Unexpected token ''', "'{"a":1}'" is not valid JSON
<!DOCTYPE html><html></html>HTML pageExpecting valueline 1 column 1 (char 0)Unexpected token '<', "<!DOCTYPE "... is not valid JSON
const cfg = {"a":1};JSON inside an assignmentExpecting 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.

The same data passed as bytes or as a decoded string
How it was readResult
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 it

What 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, Infinity and -Infinity parse by default. The strictness switch is parse_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.pos from e.doc. A single quote, a comment, or a capitalised True is 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.

Frequently asked questions

What does “Expecting value: line 1 column 1 (char 0)” mean?
It means the parser found nothing it could read as a value at the very start of the input, and gave up immediately. Python reports this one message for an empty body, an HTML page, a document wrapped in single quotes and a copied JavaScript assignment — four unrelated problems with one shared symptom, which is why the message is so unhelpful.
Why does Python say line 1 column 1 when my file has 500 lines?
Because the parser never got past the first byte. When the very first character cannot begin a value, there is no deeper position to report, so the position is the start of the input rather than the line you were editing. If you expected an error on line 300, the real problem is upstream: the response body is probably empty or is not JSON at all.
Why did “Expecting property name enclosed in double quotes” become “Illegal trailing comma”?
CPython changed that message in 3.13. On 3.9, 3.10 and 3.12 a trailing comma reports “Expecting property name enclosed in double quotes: line 1 column 9 (char 8)”. On 3.13 the same input reports “Illegal trailing comma before end of object: line 1 column 8 (char 7)”. The wording and the column both moved, so a fix written against an older traceback points one character too far right.
Why does json.loads accept a BOM when I read bytes but reject it as text?
Because the bytes path detects the encoding first. Handed bytes, Python inspects the leading bytes, recognises a BOM and decodes accordingly, including UTF-16. Handed an already-decoded string, the BOM is simply the character U+FEFF sitting where a value should be, and JSON has no meaning for it.
Does json.loads reject NaN?
No. NaN, Infinity and -Infinity are accepted by default, while V8 rejects all three. That asymmetry is why a payload can parse in a Python service and fail in the browser that receives the same bytes.
Which exception should I catch?
json.JSONDecodeError, but that is not enough on its own. If the response is not valid UTF-8, json.loads raises UnicodeDecodeError before parsing starts, and that exception does not inherit from JSONDecodeError, so a handler that catches only the JSON error will still crash on a Latin-1 byte.