Skip to content
DevTinyTools

Errors

BOM and UTF-16: when valid JSON fails

The phrase “invalid JSON” hides two different failures: the bytes never decoded, or the decoded text never parsed. Python separates them into two exceptions, but only if you feed it the right type. This guide walks through four inputs measured on CPython 3.13 and shows which layer rejects each one.

8 min readTool: JSON Validator

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 modes

The 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

How Python handles the same JSON document as bytes and as text
InputCallOutcomeWhy
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.

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'))     # accepted

The 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. UnicodeDecodeError happens before parsing; JSONDecodeError happens 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.

Frequently asked questions

Why does the same file parse as bytes but fail as text?
Python's bytes path looks at the first bytes and detects the encoding. A UTF-8 BOM is consumed, and a UTF-16 BOM selects the right codec, before the JSON parser ever sees a character. A decoded string has already crossed that boundary: the BOM is U+FEFF sitting where a value should be.
Is a BOM allowed in JSON?
RFC 8259 says implementations must not add one, and parsers may ignore it rather than treat it as an error. That latitude is why implementations differ. The practical rule is to read bytes and let the decoder decide, or strip U+FEFF before handing a string to a strict parser.
Why did my except json.JSONDecodeError not catch it?
Because invalid UTF-8 raises UnicodeDecodeError, which is a different exception and does not inherit from JSONDecodeError. Hand json.loads bytes or a file opened in binary mode and the decoder runs first; catch both exception types if the input can come from an unknown source.
Should I just use encoding='utf-8-sig'?
For a text file that may carry a BOM, yes: utf-8-sig removes the marker. For a response whose encoding is unknown, read bytes and let a detector choose. The distinction matters because a UTF-16 file opened as utf-8-sig produces NUL characters between every ASCII byte, not the document you expected.