Handling JSON Errors
External JSON data may be malformed. Trying to parse invalid JSON raises JSONDecodeError.
import json
bad_json = '{"name": "Alice", age: 30}' # Missing quotes around age
try:
data = json.loads(bad_json)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
The error tells you where parsing failed:
Expecting property name enclosed in double quotes: line 1 column 19
Always wrap loads() in try/except when dealing with external data - API responses, user input, files from unknown sources.
Common JSON syntax errors:
- Single quotes instead of double quotes
- Trailing commas after the last item
- Unquoted property names
- Comments (JSON doesn't support them)
I cover error handling patterns in my JSON with Python course.