How to Validate JSON in Python and Catch JSONDecodeError
A robust Python function that attempts to parse JSON strings and returns a boolean plus either the parsed data or a descriptive error message when decoding fails.
Python code
23 linesimport json
def validate_json(json_string):
"""Try to parse JSON, return (is_valid, data_or_error)."""
try:
data = json.loads(json_string)
return True, data
except json.JSONDecodeError as e:
return False, f"Invalid JSON: {e}"
if __name__ == "__main__":
test_inputs = [
'{"name": "Alice", "age": 30}',
'{"name": "Bob", "age": }', # Trailing comma inside
'[1, 2, 3]',
'not json at all'
]
for json_string in test_inputs:
is_valid, result = validate_json(json_string)
print(f"Input: {json_string!r}")
print(f"Valid: {is_valid}")
print(f"Result: {result}\n")
Output
Input: '{"name": "Alice", "age": 30}'
Valid: True
Result: {'name': 'Alice', 'age': 30}
Input: '{"name": "Bob", "age": }'
Valid: False
Result: Invalid JSON: Expecting value: line 1 column 19 (char 18)
Input: '[1, 2, 3]'
Valid: True
Result: [1, 2, 3]
Input: 'not json at all'
Valid: False
Result: Invalid JSON: Expecting value: line 1 column 1 (char 0)
How it works
The json.loads() function parses a JSON string into Python's native data types, such as dictionaries and lists. When the input is not valid JSON, it raises a JSONDecodeError, a subclass of ValueError. By wrapping the call in a try/except block, the function returns a tuple: (True, data) on success or (False, error_message) on failure. This pattern lets you safely handle malformed JSON without crashing your application. The function also preserves the original error message, which helps with debugging by indicating the exact line and character position of the malformed content.
Common mistakes
- Using `json.load()` on a string instead of `json.loads()` — the former expects a file object.
- Catching the generic `Exception` instead of the specific `json.JSONDecodeError`, which can hide unrelated bugs.
- Forgetting that `json.loads()` can return non-dictionary types like lists, numbers, or booleans for valid JSON.
Variations
- Use `try/except` with `json.loads()` inline without a custom function for one-off checks.
- For files on disk, use `json.load()` with a file handle managed by a `with` statement.
Real-world use cases
- Validating API request bodies in a web framework before processing them to avoid data corruption.
- Sanitizing user-submitted configuration files in a CLI tool to give clear error feedback.
- Pre-checks in data pipelines to guard against malformed JSON records from external sources.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.