Why Python cannot parse your JSON: fixing json.JSONDecodeError
Python raises json.JSONDecodeError when the text is not valid JSON. The message includes the line and column of the problem.
Common causes
- Single quotes. JSON requires double quotes around keys and strings.
{'a': 1}is a Python dict printed as text, not JSON. - Trailing commas. JSON does not allow a comma after the last item.
- Empty or non-JSON input. An empty string or an HTML error page fails at line 1 column 1. Print the raw text first.
- Wrong function. Use
json.loads(text)for a string andjson.load(file)for a file object.
Debug it
import json
text = response.text
print(repr(text[:200]))
try:
data = json.loads(text)
except json.JSONDecodeError as e:
print(e.msg, e.lineno, e.colno)If you hold a Python dict and want JSON text, use json.dumps(data).