How to Fix json.JSONDecodeError in Python
In this tutorial, you'll learn about How to Fix json.JSONDecodeError in Python. We cover key concepts, practical examples, and best practices.
Python raises json.JSONDecodeError when trying to parse a string that does not contain valid JSON.
The Wrong Way
import json
data = '{"name": "Alice", "age": }'
parsed = json.loads(data)
print(parsed)
This produces:
Traceback (most recent call last):
File "script.py", line 3, in <module>
parsed = json.loads(data)
json.JSONDecodeError: Expecting value: line 1 column 30 (char 29)
The Right Way
Validate and fix the JSON string before parsing:
import json
data = '{"name": "Alice", "age": 30}'
parsed = json.loads(data)
print(parsed)
Output:
{'name': 'Alice', 'age': 30}
Step-by-Step Fix
1. Check for empty responses
import json
response_text = "" # empty response
try:
data = json.loads(response_text)
except json.JSONDecodeError:
print("Empty or invalid JSON response")
data = {}
2. Use a validation function
import json
def safe_json_loads(text):
try:
return json.loads(text)
except (json.JSONDecodeError, TypeError) as e:
print(f"JSON decode error: {e}")
return None
result = safe_json_loads('{"key": "value"}')
print(result)
3. Validate JSON with online tools
Paste the failing JSON string into a JSON validator to find syntax errors.
4. Check for BOM markers
import json
with open('data.json', 'r', encoding='utf-8-sig') as f:
data = json.load(f)
5. Use strict=False (rarely needed)
import json
# This allows some non-standard JSON features
data = json.loads('{"key": "value"}', strict=False)
Prevention Tips
- Always validate JSON with
json.loads()inside a try-except block. - Check that API responses are not empty before parsing.
- Use
json.dumps()to serialize Python objects to valid JSON. - Validate JSON files with command-line tools like
python3 -m json.tool file.json. - Handle both JSON and non-JSON responses from external APIs gracefully.
Common Mistakes with json decode
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro