Invalid JSON
Production Risk
Common with API integrations; always handle JSONDecodeError and log the problematic input for debugging.
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.
- 1Trailing commas in JSON (valid in JS but not JSON)
- 2Single quotes instead of double quotes
- 3Unquoted keys or values (e.g., undefined, NaN, Infinity)
- 4Truncated response from a network request
- 5Parsing an HTTP error page (HTML) as JSON
Parsing a JSON response with a trailing comma.
import json
json.loads('{"key": "value",}') # Trailing comma is invalid JSONexpected 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
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 NoneWhy 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
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.
import json
json.loads('{"key": "value",}') # JSONDecodeError: trailing commaimport json
try:
data = json.loads(text)
except json.JSONDecodeError as e:
print(f"Invalid JSON at {e.lineno}:{e.colno}: {e.msg}")
data = Noneimport json
def safe_json(text: str):
try:
return json.loads(text)
except json.JSONDecodeError:
return {}✕ 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.
Python Docs — json module
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev