The Python json Module
Python ships with a built-in json module. No third-party library is required to parse or generate JSON in Python 3.
Core Functions:
json.loads(string)— Parse a JSON string into a Python dict or list.json.dumps(obj)— Serialize a Python object to a JSON string.json.load(file)— Parse JSON directly from an open file object.json.dump(obj, file)— Write JSON directly to an open file object.
Pretty Printing JSON in Python
Pass indent=2 or indent=4 to json.dumps() for human-readable output. Add sort_keys=True for alphabetically ordered keys.
Validating JSON in Python
Wrap json.loads() in a try/except block to catch json.JSONDecodeError syntax errors:
import json
# Parse JSON string
payload = '{"name": "Alice", "score": 99, "active": true}'
data = json.loads(payload)
print(data["name"]) # Alice
# Pretty print JSON
pretty = json.dumps(data, indent=2, sort_keys=True)
print(pretty)
# Validate JSON safely
def is_valid_json(text: str) -> bool:
try:
json.loads(text)
return True
except json.JSONDecodeError:
return False
# Read/Write JSON files
with open("data.json", "r") as f:
obj = json.load(f)
with open("output.json", "w") as f:
json.dump(obj, f, indent=2)