Why does Python raise "JSONDecodeError: Expecting value: line 1 column 1" and how do you fix it? | A1Lab@MZeeshanM to PythonEnglish • 6 days ago

Why does Python raise "JSONDecodeError: Expecting value: line 1 column 1" and how do you fix it?

message-square
0

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 on 204 No Content, 401 Unauthorized, 429 Too Many Requests, or 500 Internal Server Error. Calling response.json() on an empty response immediately fails at line 1 column 1.
    • Fix: Call response.raise_for_status() first and check if not response.text.strip(): before parsing.
  • 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 <!DOCTYPE html> or <html>. Because < is not a valid JSON token, json.loads() fails at character 0.
    • Fix: Inspect response.headers.get("Content-Type", "") (expecting "application/json") and log response.text[:300] to see the actual server response.
  • 3. Reading an empty or already-consumed file stream: Calling json.load(file) on a 0-byte file—or calling json.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 via file.seek(0) before re-reading.
  • 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 \ufeff at char 0, which causes json.load() to fail at line 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)
      
  • 5. Single quotes or Python dict string instead of valid JSON: Passing str(my_dict) (which uses single quotes like "{'key': 'value'}") into json.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 than str(my_dict).

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>