SyntaxStudy
Sign Up
Python Beginner 3 min read

JSON File I/O

Reading and Writing JSON Files

Use json.load() and json.dump() with file objects for reading and writing JSON files.

Example
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"))
Pro Tip

Always specify encoding="utf-8" when opening JSON files — default encoding varies by OS.