Reading and Writing JSON Files
Use json.load() and json.dump() with file objects for reading and writing JSON files.
Use json.load() and json.dump() with file objects for reading and writing JSON files.
import json
from pathlib import Path
# Write
with open("data.json", "w", encoding="utf-8") as f:
json.dump({"users": [{"id": 1, "name": "Alice"}]}, f, indent=2)
# Read
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
# Pathlib shortcut
data = json.loads(Path("data.json").read_text(encoding="utf-8"))
Always specify encoding="utf-8" when opening JSON files — default encoding varies by OS.