Two failures called invalid JSON
A decoder turns bytes into a string. A parser turns that string into a value. They raise different exceptions, but logs usually collapse both into “invalid JSON”. That is why a payload that looks fine in an editor can fail in one service and pass in another: the two services hand different types to the parser.
value = json.loads(response.content) # bytes
value = json.loads(response.content.decode()) # str
# same bytes, two different failure modesThe measurements below were produced by scripts/measure-python-json.py under CPython 3.13.12. The script is in the public repository, so each row can be reproduced with one command.
Four inputs, measured
| Input | Call | Outcome | Why |
|---|---|---|---|
| UTF-8 file with a BOM, read as bytes | json.loads(open(path, 'rb').read()) | accepted | Bytes are decoded with BOM detection, so the BOM is removed before parsing starts. |
| The same file, read as text | json.loads(open(path, encoding='utf-8').read()) | rejected | The BOM survives as U+FEFF, which is not whitespace and not a value. |
| A UTF-16 encoded document, read as bytes | json.loads('{"a":1}'.encode('utf-16')) | accepted | The BOM in the first bytes is enough for Python to pick the UTF-16 codec. |
| Latin-1 bytes | json.loads(b'{"name": "caf\xe9"}') | UnicodeDecodeError | Not a JSON error at all, so `except json.JSONDecodeError` does not catch it. |
Read the first two rows together. The file is identical; only the type handed to json.loads changed. One path removes the BOM as part of decoding, the other leaves it in the string where the parser expects {, [, a quote, a digit, true, false or null.
UTF-16 is not double-width ASCII
A UTF-16 encoded {"a":1} begins with a byte-order mark. Hand those bytes to json.loads and Python selects the codec, decodes the document and parses it. Hand the same bytes to a parser that assumes UTF-8 and each ASCII character arrives followed by a NUL byte, which no JSON parser accepts as whitespace.
raw = '{"a":1}'.encode('utf-16')
json.loads(raw) # accepted
json.loads(raw.decode('utf-8')) # UnicodeDecodeError
json.loads(raw.decode('utf-16')) # acceptedThe lesson is not that UTF-16 is common. It is that the encoding decision belongs to the byte layer, and a string that has already been decoded cannot tell you which codec was used.
Handle it in order
- Keep the bytes. Read the response body as bytes and let the decoder inspect the BOM. Do not decode early “just to see what it says”.
- Catch both exceptions.
UnicodeDecodeErrorhappens before parsing;JSONDecodeErrorhappens inside it. - Print the first bytes.
repr(body[:40])separates an empty body, an HTML page, a BOM and a UTF-16 payload faster than any error message. - Validate before upload. The browser validator reports the exact character where parsing stopped, without sending the document anywhere.