Working with JSON files in Python
json module, json.loads, json.dumps, json.load, json.dump, indent parameter, Python-JSON type mapping, handling JSONDecodeError
JSON in Python
The json module converts between Python objects and JSON strings/files. dumps and loads work with strings. dump and load work with file objects.
import json
# Python → JSON string
data = {"name": "Alice", "scores": [95, 87, 92], "active": True}
json_str = json.dumps(data, indent=2)
print(json_str)
# JSON string → Python
parsed = json.loads(json_str)
print(parsed["name"]) # Alice
# Write to file
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read from file
with open("data.json", "r") as f:
loaded = json.load(f)
Type Mapping
JSON maps to Python as: object → dict, array → list, string → str, number → int or float, true/false → True/False, null → None. Python set, tuple, and custom objects are not JSON-serialisable by default — convert them first or provide a custom encoder.
try:
json.loads("not valid json")
except json.JSONDecodeError as e:
print(f"Bad JSON: {e}")
JSON is the most common data exchange format for web APIs and configuration files. Python's json module handles the most common types automatically. For custom objects, implement a default function and pass it to json.dumps — it receives objects the encoder cannot handle and should return a serialisable equivalent. The sort_keys=True option produces deterministic output useful for testing and version control diffs. When reading untrusted JSON (from a network or user), always validate the structure before accessing keys — do not assume the shape matches your expectations.
