Common causes
1. The HTTP response body is empty
A 204 reply, a failed request or a server that crashed before writing returns an empty body, and response.json() fails at char 0. Check the status and the body before decoding.
resp = requests.get(url, timeout=10)
data = resp.json()resp = requests.get(url, timeout=10)
resp.raise_for_status()
data = resp.json() if resp.content else None2. The response is HTML or plain text, not JSON
Error pages from nginx, Cloudflare or an Envoy sidecar, login pages and rate-limit notices are not JSON. raise_for_status() does not help when the page arrives with status 200, so check the content type and log the start of the body. See also Unexpected token ‘<’.
data = resp.json()if "application/json" not in resp.headers.get("Content-Type", ""):
raise RuntimeError(f"{resp.status_code} from {resp.url}: {resp.text[:200]!r}")
data = resp.json()3. json.loads given a file name instead of file contents
json.loads("config.json") tries to parse the eleven characters of the file name. Use json.load with an open file, or read the file first.
config = json.loads("config.json")with open("config.json", encoding="utf-8") as f:
config = json.load(f)4. The file was already read to the end
After f.read() the file position is at the end, so a following json.load(f) reads an empty string. Parse the text you already have, or f.seek(0) first. The same thing happens when a stream or an HTTP response object is consumed twice.
with open("data.json", encoding="utf-8") as f:
print(f.read())
data = json.load(f)with open("data.json", encoding="utf-8") as f:
text = f.read()
print(text)
data = json.loads(text)5. A missing value inside the document
When the column is not 1, a value is missing or invalid at that spot: an empty slot after a colon, a trailing comma in an array, or a word like undefined or True.
{"order_id": 1182, "discount": , "currency": "EUR"}{"order_id": 1182, "discount": null, "currency": "EUR"}Read the exception before guessing
JSONDecodeError carries everything you need. msg is the message, doc the full text, pos the offset, and lineno and colno the location:
try:
data = json.loads(text)
except json.JSONDecodeError as err:
start = max(err.pos - 40, 0)
print(err.msg, err.lineno, err.colno)
print(repr(err.doc[start:err.pos + 40]))
raise
The exact input explains the exact position:
''fails atline 1 column 1 (char 0). The text is empty.' 'fails atline 1 column 4 (char 3). Whitespace is skipped, so the error sits at the end.'\n'fails atline 2 column 1 (char 1). This is the usual sign of a blank line in JSON Lines.'<!DOCTYPE html>'fails at char 0, as does any other text that does not begin a value.- A string starting with a BOM gets its own message:
Unexpected UTF-8 BOM (decode using utf-8-sig).
Passing None is a different failure again: TypeError: the JSON object must be str, bytes or bytearray, not NoneType. If you see that, the variable was never set.
Checks that catch most HTTP cases
Work through these in order against the failing response:
- Print
resp.status_code,resp.urlandresp.headers.get("Content-Type"). A redirect may have landed you somewhere unexpected. - Print
repr(resp.text[:500]). An empty string, an HTML tag or a plain sentence each point to a different cause. - Look at
resp.content[:20]if the text looks like noise. A compressed body can reach you undecoded when you copiedAccept-Encoding: gzip, deflate, brfrom a browser and no Brotli package is installed. Remove that header and let requests negotiate. - Try the same request with
curl -i. If curl gets JSON, compare headers: a missingAcceptorUser-Agentoften changes what a server or firewall returns.
Other clients differ slightly. httpx raises the standard json.JSONDecodeError. aiohttp checks the header first and raises ContentTypeError: Attempt to decode JSON with unexpected mimetype: text/html unless you pass content_type=None.
Files, pipes and subprocess output
The error is not only an HTTP problem. For JSON Lines, skip blank lines rather than decoding them, and include the line number in any failure:
with open("events.jsonl", encoding="utf-8") as f:
for number, line in enumerate(f, 1):
if line.strip():
handle(json.loads(line))
With subprocess.run, check returncode before parsing stdout: a failed command usually writes nothing there and its explanation to stderr. Tools that print a banner or warning on stdout before their JSON produce this same error at char 0.
For a Windows file with a BOM, open it with encoding="utf-8-sig", or pass raw bytes to json.loads, which detects the encoding itself. See the Python JSON guide for more.
Frequently asked questions
What does "char 0" mean?
It is the zero-based character offset of the problem, so char 0 is the very first character. Combined with line 1 column 1 it almost always means the input is empty or is not JSON at all.
Why does requests raise requests.exceptions.JSONDecodeError?
Since requests 2.27, response.json() wraps the decoder error in its own class so one except clause works everywhere. It inherits from json.JSONDecodeError, or from simplejson’s class when simplejson is installed, so catch the requests class to be safe.
How do I see what Python actually received?
Print repr(resp.text[:500]) or repr(text[:500]) before decoding. repr shows an empty string as ‘’ and makes invisible characters such as a BOM or stray whitespace visible.
Should I catch this error or prevent it?
Both. Check the status and content type first, then wrap the decode in a try block that logs the start of the body. Avoid an empty except clause that returns {}, because it hides outages as missing data.
Why is NaN accepted but undefined is not?
Python’s decoder accepts NaN, Infinity and -Infinity as an extension to the standard, while undefined is not a value it knows. Other parsers reject all of them, so avoid NaN in data other programs read.