0
0
PythonHow-ToBeginner · 3 min read

How to Validate JSON in Python: Simple Guide with Examples

To validate JSON in Python, use the json.loads() function to parse a JSON string. If the string is not valid JSON, it will raise a json.JSONDecodeError, which you can catch to handle invalid data.
📐

Syntax

The main function to validate JSON in Python is json.loads(). It takes a JSON string as input and tries to convert it into Python objects.

  • json.loads(json_string): Parses the JSON string.
  • If the JSON is valid, it returns the corresponding Python data (like dict or list).
  • If invalid, it raises json.JSONDecodeError.
python
import json

json.loads(json_string)
💻

Example

This example shows how to check if a JSON string is valid by trying to parse it and catching errors if it is not valid.

python
import json

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

try:
    data = json.loads(json_string)
    print("Valid JSON:", data)
except json.JSONDecodeError as e:
    print("Invalid JSON:", e)
Output
Valid JSON: {'name': 'Alice', 'age': 30}
⚠️

Common Pitfalls

Common mistakes when validating JSON include:

  • Passing a Python dictionary directly to json.loads() instead of a JSON string.
  • Not catching json.JSONDecodeError, which causes the program to crash on invalid JSON.
  • Assuming JSON keys are always strings; JSON requires keys to be strings.

Always ensure your input is a string and handle exceptions properly.

python
import json

# Wrong: Passing dict instead of string
try:
    json.loads({"name": "Bob"})
except TypeError as e:
    print("Error:", e)

# Right: Pass string and catch JSONDecodeError
json_string = '{"name": "Bob"}'  # Invalid JSON (keys must be in quotes)
try:
    json.loads(json_string)
except json.JSONDecodeError as e:
    print("Invalid JSON:", e)
Output
Error: the JSON object must be str, bytes or bytearray, not dict Invalid JSON: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
📊

Quick Reference

Tips for JSON validation in Python:

  • Use json.loads() to parse JSON strings.
  • Catch json.JSONDecodeError to handle invalid JSON gracefully.
  • Ensure JSON keys are double-quoted strings.
  • Use json.dumps() to convert Python objects to JSON strings.

Key Takeaways

Use json.loads() to validate JSON strings in Python.
Catch json.JSONDecodeError to handle invalid JSON without crashing.
Always pass a JSON string, not a Python dict, to json.loads().
JSON keys must be double-quoted strings to be valid.
Use json.dumps() to convert Python objects back to JSON strings.