Python JSONDecodeError: Expecting value line 1 column 1
Column 1 means the body starts with something that is not JSON: an HTML error page, an empty response, a BOM, or an already consumed stream.

Introduction & Quick Summary
Parsing a response or file fails at its very first byte:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
column 1, char 0 means the parser found nothing parseable at the start of the input. This is almost never a bug in the JSON you wrote: it is the wrong document entirely — an empty body, an HTML error page, a BOM, or a stream that was already consumed.
Where it appears:
requestscalling.json()on a 404 or 502 page that returned HTML.- A proxy or WAF returning a login page with status 200.
- An API that returns
204 No Content, so the body is empty. json.load(f)on an empty file, or on a file opened withencoding="utf-8"that begins with a BOM.- Reading
response.textafterresponse.raw.read(), which leaves nothing for the parser. - A gzip or brotli body read through
rawwithout decompression, producing binary garbage.
Quick answer: print the status, the content type, and the first 200 characters of the body before parsing. In nearly every case the body is HTML or empty, and the fix is to check the response instead of the JSON.
Core Mechanics, Signatures & Reproducible Setup
json.loads requires one complete JSON value and nothing else. It raises JSONDecodeError with msg, doc, pos, lineno, and colno; char 0 is the absolute offset, so the pair line 1 column 1 (char 0) pins the failure to the first character of the input.
Reproduce each variant locally:
import json
for payload in ["", " ", "<html><body>502 Bad Gateway</body></html>", "\ufeff{\"ok\": true}", "{\"a\": 1} trailing"]:
try:
json.loads(payload)
print("parsed:", repr(payload))
except json.JSONDecodeError as exc:
print(f"{exc.msg!r} pos={exc.pos} for {payload[:20]!r}")Expecting value pos=0 for ''
Expecting value pos=1 for ' '
Expecting value pos=0 for '<html><body>502 Bad '
Expecting value pos=0 for '\ufeff{"ok": true}'
Extra data pos=8 for '{"a": 1} trailing'Note the BOM case: the BOM is a character the parser does not accept, and Python reports it as Expecting value at position 0 even though valid JSON follows. Decoding with utf-8-sig removes it.
The error message tells you which fix applies:
| Message | Position clue | Meaning | Fix |
|---|---|---|---|
Expecting value | char 0 | empty body, HTML, BOM, binary | check status and content type first |
Expecting value | mid-document | truncated body, stream cut early | retry or fix the server |
Expecting property name enclosed in double quotes | mid | single quotes or trailing comma | fix the producer |
Extra data | after a value | concatenated documents or a log line | split the stream |
Unterminated string starting at | mid | truncated payload | retry with a larger limit |
Key Comparison Table
The four ways a .json() call fails, and what each one needs:
| Symptom | Body starts with | Status | Fix |
|---|---|---|---|
| HTML error page | <!DOCTYPE, <html | 404, 500, 502 | raise_for_status() before parsing |
| WAF or login page | <html | 200 | send the right headers, or detect and re-authenticate |
| Empty body | nothing | 204, 304 | handle "no content" explicitly |
| Truncated JSON | { with no close | 200 | retry; check Content-Length |
| BOM prefixed | \ufeff{ | 200 | decode with utf-8-sig |
| Binary | \x1f\x8b (gzip) | 200 | decompress, or use .json() on the wrapper |
Which API to reach for:
| Call | On a 404 HTML page | On empty body | Notes |
|---|---|---|---|
response.json() | raises JSONDecodeError | raises JSONDecodeError | no status check |
response.json() after raise_for_status() | raises HTTPError | still raises JSONDecodeError | better errors |
json.loads(response.text) | same | same | lets you inspect first |
response.json(strict=False) | same | same | only relaxes control characters |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Check the status before trusting the body
The single change that removes most of these incidents:
import requests
from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError
def get_json(url: str, **kwargs):
response = requests.get(url, timeout=10, **kwargs)
response.raise_for_status() # 4xx/5xx become HTTPError
if not response.content:
raise ValueError(f"empty body from {url} (status {response.status_code})")
ctype = response.headers.get("content-type", "")
if "json" not in ctype:
raise ValueError(f"expected JSON from {url}, got {ctype}: {response.text[:200]!r}")
try:
return response.json()
except RequestsJSONDecodeError as exc:
raise ValueError(f"invalid JSON from {url}: {exc} — body starts {response.text[:200]!r}") from excThe content-type check catches the 200-with-HTML case that raise_for_status cannot see, which is exactly the case a proxy or captive portal produces.
2. Empty bodies are a normal outcome
204 No Content and 304 Not Modified are successes with no body, and code that assumes JSON breaks on the first one:
if response.status_code == 204:
return None
if response.status_code == 304:
return cached_valueThe same applies to HEAD requests and to endpoints that answer 202 Accepted with an empty body and a Location header. Parse the Location header instead of the body.
3. File input: BOM, encoding, and empty files
Reading a file written by Windows tooling is the second most common source:
from pathlib import Path
import json
text = Path("config.json").read_text(encoding="utf-8-sig") # strips the BOM
if not text.strip():
raise ValueError("config.json is empty")
data = json.loads(text)json.load(open(path)) with the platform default encoding fails on Windows for non-ASCII content and hides a BOM on every platform. Always name the encoding, and use utf-8-sig for input that may have been produced by another tool.
4. Streaming responses read twice
A stream can only be consumed once:
response = requests.get(url, stream=True)
raw = response.raw.read() # consumes the stream
body = response.text # empty
json.loads(body) # Expecting value: line 1 column 1 (char 0)Read once into a variable and parse that variable, or use response.iter_content with an explicit bytearray buffer. With httpx, response.read() caches the content, so the same mistake behaves differently between the two libraries.
5. Compressed bodies that bypass decoding
When Content-Encoding: gzip is handled by response.raw instead of the library, the bytes are compressed and the parser sees \x1f\x8b:
import gzip
raw = response.raw.read()
if response.headers.get("content-encoding") == "gzip":
raw = gzip.decompress(raw)
data = json.loads(raw.decode("utf-8"))Prefer response.content, which already decodes the transfer encoding, and check the first bytes when the message says Expecting value on a body that looks non-empty in a hex dump.
Common Compilation/Runtime Mistakes & Version Gotchas
Wrapping the call in except Exception: pass. Swallowing the error turns a proxy outage into a downstream NoneType failure with no context. Catch JSONDecodeError and re-raise with the status, URL, and body prefix, or let it propagate.
Calling .json() twice on a streamed response. The second call sees an exhausted stream and raises the same error. Cache the parsed object.
Assuming a JSON content type guarantees valid JSON. A misconfigured server can label HTML as application/json; the parser then reports Expecting value at position 0 with an HTML body. Log the first bytes, not just the header.
Version differences worth knowing. requests vendors its own JSONDecodeError (a subclass of simplejson's error when installed), so except json.JSONDecodeError can miss it — catch requests.exceptions.JSONDecodeError or ValueError to cover both. Python 3.11 added JSONDecodeError positions to error messages in more places, which changes how the text reads but not the exception type. httpx 0.27 changed how response.text handles undecodable bytes, returning replacement characters where older versions raised.
Inspecting the body before parsing. Validate a suspicious payload with the JSON formatter, and confirm what the endpoint actually returns with the cURL helper plus the HTTP status reference before changing the Python code.
Reference material: Python json module, JSONDecodeError and requests quickstart, JSON response content.
Official references
primary documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython Typer Rich Integration and Progress Bars
python typer rich integration and progress bars: Learn to integrate Rich progress bars into Typer CLI applications, covering track, Progress, dynamic.
Python Wildcard Pattern Matching with fnmatch and glob
Learn Python's wildcard pattern matching with fnmatch, glob, and pathlib to filter strings and file paths using *, ?, and character sets.
Python 3.14 PEP 649: NameError from lazy annotations
Annotations are no longer strings. A NAME only imported under TYPE_CHECKING now raises when FastAPI or Pydantic reads the signature.
asyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.