How to Fix Python JSON Decode Error
In this tutorial, you'll learn about How to Fix Python JSON Decode Error. We cover key concepts, practical examples, and best practices.
The Problem
You parse a JSON string or file and get:
Traceback (most recent call last):
File "script.py", line 5, in <module>
data = json.loads(content)
File "/usr/lib/python3.10/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.10/json/__init__.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Python's JSON parser expects strictly valid JSON. Single quotes, trailing commas, or comments that are valid in JavaScript will cause this error.
Quick Fix
Step 1: Validate the JSON
Use Python to validate your JSON string:
python3 -c "import json; json.loads(open('file.json').read())"
If it fails, the error message points to the exact location.
Step 2: Fix common JSON issues
import json
# Wrong -- single quotes
data = json.loads("{'name': 'Alice'}")
# Right -- double quotes
data = json.loads('{"name": "Alice"}')
Remove trailing commas:
# Wrong
data = json.loads('{"items": [1, 2, 3,]}')
# Right
data = json.loads('{"items": [1, 2, 3]}')
Step 3: Handle empty files
Check if the file has content before parsing:
import os
if os.path.getsize("file.json") == 0:
data = {}
else:
with open("file.json") as f:
data = json.load(f)
Step 4: Fix encoding issues
Specify the encoding when opening the file:
with open("file.json", encoding="utf-8") as f:
data = json.load(f)
Alternative Solutions
Use json.decoder.JSONDecoder with strict=False to allow some non-standard JSON:
decoder = json.decoder.JSONDecoder(strict=False)
data = decoder.decode(content)
For truly malformed JSON, try demjson3:
pip install demjson3
python3 -c "import demjson3; print(demjson3.decode(open('file.json').read()))"
Verify Your Python Environment
python3 --version
# Python 3.10.12
pip list | grep requests
# requests 2.31.0
Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.
Additional Troubleshooting
# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"
If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.
Prevention
- Validate JSON with
python3 -m json.tool file.jsonbefore processing. - Use a JSON linter in your editor.
- Generate JSON with
json.dumps()rather than writing it by hand. - Always wrap
json.loads()in a try-except block.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro