Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readPython
#python#json#requests#http
Bold white headline reading BAD JSON with a Python response crate holding an amber HTML page card on the right.

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:

  • requests calling .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 with encoding="utf-8" that begins with a BOM.
  • Reading response.text after response.raw.read(), which leaves nothing for the parser.
  • A gzip or brotli body read through raw without 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:

python
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}")
code
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:

MessagePosition clueMeaningFix
Expecting valuechar 0empty body, HTML, BOM, binarycheck status and content type first
Expecting valuemid-documenttruncated body, stream cut earlyretry or fix the server
Expecting property name enclosed in double quotesmidsingle quotes or trailing commafix the producer
Extra dataafter a valueconcatenated documents or a log linesplit the stream
Unterminated string starting atmidtruncated payloadretry with a larger limit

Key Comparison Table

The four ways a .json() call fails, and what each one needs:

SymptomBody starts withStatusFix
HTML error page<!DOCTYPE, <html404, 500, 502raise_for_status() before parsing
WAF or login page<html200send the right headers, or detect and re-authenticate
Empty bodynothing204, 304handle "no content" explicitly
Truncated JSON{ with no close200retry; check Content-Length
BOM prefixed\ufeff{200decode with utf-8-sig
Binary\x1f\x8b (gzip)200decompress, or use .json() on the wrapper

Which API to reach for:

CallOn a 404 HTML pageOn empty bodyNotes
response.json()raises JSONDecodeErrorraises JSONDecodeErrorno status check
response.json() after raise_for_status()raises HTTPErrorstill raises JSONDecodeErrorbetter errors
json.loads(response.text)samesamelets you inspect first
response.json(strict=False)samesameonly 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:

python
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 exc

The 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:

python
if response.status_code == 204: return None if response.status_code == 304: return cached_value

The 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:

python
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:

python
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:

python
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 documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.