JSON Errors
Handle malformed JSON with json.JSONDecodeError. Catch it at API and file boundaries.
Handle malformed JSON with json.JSONDecodeError. Catch it at API and file boundaries.
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
JSONDecodeError is a subclass of ValueError — catching ValueError also works but is less specific.