How to read and write JSON files in Python
Complete guide to Python's json module: json.load(), json.loads(), json.dump(), json.dumps(), and common errors — with real-world examples.
Python's built-in json module handles all JSON serialization and deserialization. No third-party packages are needed for standard JSON work.
Reading JSON from a string
import json
raw = '{"name": "Ada", "age": 30, "active": true}'
data = json.loads(raw) # loads = load string
print(data["name"]) # Ada
print(data["age"]) # 30
print(type(data)) # <class 'dict'>Reading a JSON file
import json
with open("data.json", encoding="utf-8") as f:
data = json.load(f) # load (no 's') reads from a file object
print(data) # Python dict or listAlways specify encoding='utf-8' to avoid platform-dependent encoding issues, especially on Windows.
Writing JSON to a string
import json
data = {"name": "Ada", "scores": [98, 87, 95], "active": True}
compact = json.dumps(data)
# '{"name": "Ada", "scores": [98, 87, 95], "active": true}'
pretty = json.dumps(data, indent=2)
# {
# "name": "Ada",
# "scores": [98, 87, 95],
# "active": true
# }Writing a JSON file
import json
data = {"name": "Ada", "age": 30}
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2) # dump (no 's') writes to a file objectHandling JSONDecodeError
import json
def safe_parse(text: str):
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
result = safe_parse('{"broken": }')
# Invalid JSON at line 1, col 12: Expecting valueType mapping: JSON to Python
# JSON → Python # object → dict # array → list # string → str # number (int) → int # number (float)→ float # true → True # false → False # null → None
Sorting keys and controlling output
json.dumps(data, sort_keys=True) # alphabetical key order
json.dumps(data, indent=2, sort_keys=True) # pretty + sorted
json.dumps(data, ensure_ascii=False) # allow non-ASCII chars (e.g. emoji, CJK)
json.dumps(data, separators=(',', ':')) # compact, no spacesCustom serialization with default
import json
from datetime import datetime, date
def json_default(obj):
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError(f"Object of type {type(obj)} is not JSON serializable")
data = {"name": "Ada", "joined": datetime(2024, 1, 15)}
json.dumps(data, default=json_default)
# '{"name": "Ada", "joined": "2024-01-15T00:00:00"}'Find the problem with the JSON linter →
The linter surfaces trailing commas, duplicate keys, and other common issues with line and column numbers.
Open JSON Linter →