SyntaxStudy
Sign Up
Python Beginner 3 min read

JSON Error Handling

JSON Errors

Handle malformed JSON with json.JSONDecodeError. Catch it at API and file boundaries.

Example
import json

def safe_parse(text: str) -> dict | None:
    try:
        return json.loads(text)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON at line {e.lineno}, col {e.colno}: {e.msg}")
        return None

data = safe_parse('{"key": "value"}')   # OK
bad  = safe_parse('not json at all')     # None + error message
Pro Tip

JSONDecodeError is a subclass of ValueError — catching ValueError also works but is less specific.