Python raises json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) when json.loads() or json.load() receives an empty string (""), whitespace-only input, or non-JSON content (such as an HTML error page or plain text) starting at the very first character (char 0). Fix it by validating that the response/file content is non-empty, checking HTTP status codes and Content-Type headers before calling .json(), and wrapping parsing in a try...except json.JSONDecodeError block.
Basic Example
import json
import requests
response = requests.get("[https://api.example.com/data](https://api.example.com/data)", timeout=10)
# 1. Verify HTTP success and non-empty body before decoding JSON
if response.ok and response.text.strip():
try:
data = response.json()
except json.JSONDecodeError as err:
print(f"Invalid JSON payload: {err}")
print(f"Raw response preview: {response.text[:200]}")
else:
print(f"Empty or failed response (HTTP {response.status_code})")
Common Root Causes & Targeted Fixes
- 1. Empty HTTP response body (
204 No Content, rate limits, or server errors): Many APIs return an empty body on204 No Content,401 Unauthorized,429 Too Many Requests, or500 Internal Server Error. Callingresponse.json()on an empty response immediately fails atline 1 column 1.- Fix: Call
response.raise_for_status()first and checkif not response.text.strip():before parsing.
- Fix: Call
- 2. Server returned HTML or XML instead of JSON: When an API endpoint URL is wrong, behind a login wall, or blocked by a WAF/Cloudflare proxy, the server returns an HTML page starting with
or<html>. Because<is not a valid JSON token,json.loads()fails at character0.- Fix: Inspect
response.headers.get("Content-Type", "")(expecting"application/json") and logresponse.text[:300]to see the actual server response.
- Fix: Inspect
- 3. Reading an empty or already-consumed file stream: Calling
json.load(file)on a0-byte file—or callingjson.load(file)a second time on the same open file handle after the cursor is already at EOF—passes""to the parser.- Fix: Check file size (
path.stat().st_size > 0) or reset the file pointer viafile.seek(0)before re-reading.
- Fix: Check file size (
- 4. UTF-8 Byte Order Mark (
\ufeff) at the start of a file: Files saved with UTF-8 BOM (common on Windows) start with the invisible character\ufeffatchar 0, which causesjson.load()to fail atline 1 column 1.- Fix: Open the file with
encoding="utf-8-sig"instead of"utf-8"so Python automatically strips the leading BOM:import json with open("data.json", "r", encoding="utf-8-sig") as file: data = json.load(file)
- Fix: Open the file with
- 5. Single quotes or Python dict string instead of valid JSON: Passing
str(my_dict)(which uses single quotes like"{'key': 'value'}") intojson.loads()fails at column 2 or column 1 depending on leading characters, because the JSON standard strictly requires double quotes (").- Fix: Serialize dictionaries with
json.dumps(my_dict)rather thanstr(my_dict).
- Fix: Serialize dictionaries with
Root Cause & Diagnostic Reference
| Root Cause | What char 0 Actually Contains |
Diagnostic Check | Fix |
|---|---|---|---|
Empty response or 0-byte file |
EOF (nothing at char 0) |
len(text.strip()) == 0 |
Guard with if text.strip(): or handle 204 No Content separately. |
| HTML error / login page | < (from <html> or `<!DOCTYPE> |
You must log in or register to comment.
