SyntaxStudy
Sign Up
Python JSON File Handling
Python Beginner 8 min read

JSON File Handling

JSON File Handling

The json module converts between Python objects and JSON strings/files. It is the standard format for configuration files and APIs.

Writing JSON to File

import json

data = {
    "name": "Alice",
    "age": 30,
    "scores": [95, 87, 92],
    "address": {"city": "NYC", "zip": "10001"}
}

with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=4, ensure_ascii=False)

Reading JSON from File

with open("data.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)

print(loaded["name"])           # Alice
print(loaded["scores"][0])      # 95
print(loaded["address"]["city"]) # NYC

String Serialization

json_str = json.dumps(data, indent=2)
print(json_str)

parsed = json.loads(json_str)
print(type(parsed))  # dict

Custom Serialization

from datetime import datetime

def json_serial(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Type {type(obj)} not serializable")

data = {"ts": datetime.now()}
print(json.dumps(data, default=json_serial))
Example
import json

config = {
    "database": {"host": "localhost", "port": 5432},
    "debug": True,
    "allowed_hosts": ["localhost", "127.0.0.1"]
}

json_str = json.dumps(config, indent=2)
print(json_str)

parsed = json.loads(json_str)
print(parsed["database"]["port"])  # 5432
print(type(parsed["allowed_hosts"]))  # list
Pro Tip

json.dumps() creates a string; json.dump() writes to a file. Similarly, json.loads() parses a string; json.load() reads from a file.