0
0
PythonDebug / FixBeginner · 3 min read

How to Handle JSON Decode Error in Python: Simple Fixes

A json.decoder.JSONDecodeError happens when Python tries to read invalid JSON data. To handle it, use a try-except block around json.loads() or json.load() to catch the error and respond gracefully.
🔍

Why This Happens

This error occurs when Python tries to convert a string or file into JSON but the data is not properly formatted. Common causes include missing quotes, extra commas, or incomplete JSON structure.

python
import json

broken_json = '{"name": "Alice", "age": 30}'  # age key missing quotes fixed

# This will not raise JSONDecodeError
json.loads(broken_json)
🔧

The Fix

Wrap your JSON parsing code in a try-except block to catch JSONDecodeError. This lets your program handle bad JSON without crashing.

python
import json

broken_json = '{"name": "Alice", age: 30}'

try:
    data = json.loads(broken_json)
except json.decoder.JSONDecodeError as e:
    print(f"JSON decode error: {e}")
    data = None

print(data)
Output
JSON decode error: Expecting property name enclosed in double quotes: line 1 column 17 (char 16) None
🛡️

Prevention

To avoid JSON decode errors, always ensure your JSON data is valid before parsing. Use online JSON validators or Python tools like json.tool to check format. When reading from files or APIs, validate the input or handle exceptions gracefully.

Also, consider these best practices:

  • Use json.dumps() to create JSON strings instead of writing manually.
  • Validate external JSON data before processing.
  • Use logging to record errors for debugging.
⚠️

Related Errors

Other common JSON-related errors include:

  • TypeError: When trying to serialize unsupported Python objects with json.dumps().
  • UnicodeDecodeError: When reading JSON files with wrong encoding.
  • ValueError: When input is not a string or bytes for json.loads().

Handling these requires checking data types and encoding before parsing or serializing.

Key Takeaways

Always use try-except to catch json.decoder.JSONDecodeError when parsing JSON.
Validate JSON data format before parsing to prevent errors.
Use json.dumps() to generate JSON strings safely.
Log errors to help diagnose JSON issues in your code.
Be aware of related errors like TypeError and UnicodeDecodeError.