json.JSONDecodeError
PythonERRORNotableValue ErrorHIGH confidence

Invalid JSON

Production Risk

Common with API integrations; always handle JSONDecodeError and log the problematic input for debugging.

What this means

A subclass of ValueError raised by json.loads() and json.load() when the input is not valid JSON. It includes the exact position of the parse error.

Why it happens
  1. 1Trailing commas in JSON (valid in JS but not JSON)
  2. 2Single quotes instead of double quotes
  3. 3Unquoted keys or values (e.g., undefined, NaN, Infinity)
  4. 4Truncated response from a network request
  5. 5Parsing an HTTP error page (HTML) as JSON
How to reproduce

Parsing a JSON response with a trailing comma.

trigger — this will error
trigger — this will error
import json
json.loads('{"key": "value",}')  # Trailing comma is invalid JSON

expected output

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 20 (char 19)

Fix 1

Validate and handle JSONDecodeError

WHEN Parsing user-supplied or external JSON data

Validate and handle JSONDecodeError
import json

def safe_parse(text):
    try:
        return json.loads(text)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON at line {e.lineno}, col {e.colno}: {e.msg}")
        print(f"Near: {text[max(0,e.pos-20):e.pos+20]!r}")
        return None

Why this works

JSONDecodeError.pos, .lineno, and .colno pinpoint the exact error location.

Fix 2

Check HTTP response content type before parsing

WHEN Parsing API responses

Check HTTP response content type before parsing
import requests
import json

resp = requests.get('https://api.example.com/data')
resp.raise_for_status()  # Raise for 4xx/5xx before parsing

if 'application/json' not in resp.headers.get('Content-Type', ''):
    raise ValueError(f"Expected JSON, got {resp.headers['Content-Type']}")
data = resp.json()

Why this works

Checking Content-Type before parsing prevents attempting to parse HTML error pages as JSON.

Code examples
Triggerpython
import json
json.loads('{"key": "value",}')  # JSONDecodeError: trailing comma
Handle with try/exceptpython
import json
try:
    data = json.loads(text)
except json.JSONDecodeError as e:
    print(f"Invalid JSON at {e.lineno}:{e.colno}: {e.msg}")
    data = None
Avoid with validation before parsingpython
import json
def safe_json(text: str):
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        return {}
What not to do

Use eval() instead of json.loads() to handle non-strict JSON

eval() is a remote code execution vulnerability; use a dedicated JSON5 library for relaxed JSON parsing.

Sources
Official documentation ↗

Python Docs — json module

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors