Python · Module 8 · Lesson 31 min read

JSON Serialization

JSON

The standard text format for APIs, config files and saving app data. It maps neatly onto Python:

JSONPython
object {}dict
array []list
stringstr
numberint / float
true / falseTrue / False
nullNone

Four functions to remember

FunctionConverts
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=2 gives pretty, readable output.
  • ensure_ascii=False keeps non-English text readable ("नमस्ते" instead of \u0928…).
  • sort_keys=True gives 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

Python
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}