JSON Serialization
JSON
The standard text format for APIs, config files and saving app data. It maps neatly onto Python:
| JSON | Python |
|---|---|
object {} | dict |
array [] | list |
| string | str |
| number | int / float |
true / false | True / False |
null | None |
Four functions to remember
| Function | Converts |
|---|---|
json.dumps(obj) | Python → JSON string |
json.loads(text) | JSON string → Python |
json.dump(obj, f) | Python → JSON file |
json.load(f) | JSON file → Python |
| (The "s" means string.) |
Useful options
indent=2gives pretty, readable output.ensure_ascii=Falsekeeps non-English text readable ("नमस्ते"instead of\u0928…).sort_keys=Truegives stable output.
⚠️ Keys always become strings and tuples become lists. Dates and custom objects can't be saved directly: convert them first (date.isoformat(), dataclasses.asdict()).
▶️ Runs in the app.
Example
import json
from dataclasses import dataclass, asdict
data = {"name": "Ana", "skills": ["Python", "SQL"], "active": True, "manager": None}
text = json.dumps(data, indent=2)
print(text)
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
with open("data.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["skills"]) # ['Python', 'SQL']
@dataclass
class User:
name: str
age: int
print(json.dumps(asdict(User("Ben", 30)))) # {"name": "Ben", "age": 30}