Python - JSON
Overview
Estimated time: 15–25 minutes
Read and write JSON using Python's built-in json module, including files and pretty-printing.
Learning Objectives
- Serialize Python objects to JSON with json.dumps/json.dump.
- Parse JSON strings/files with json.loads/json.load.
- Handle non-serializable types by customizing encoding.
Prerequisites
Parsing and serializing
import json
obj = {"name": "Ada", "skills": ["math", "programming"], "active": True}
text = json.dumps(obj)
print(text)
print(json.loads(text)["name"])  # Ada
Files and pretty-printing
import json
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(obj, f, ensure_ascii=False, indent=2)
Custom encoding
from datetime import datetime
import json
def encode(o):
    if isinstance(o, datetime):
        return o.isoformat()
    raise TypeError(f"Type {type(o)} not serializable")
print(json.dumps({"now": datetime.now()}, default=encode))
Common Pitfalls
- Serializing non-JSON types (e.g., datetime) without a custom encoder.
- Forgetting ensure_ascii=Falsefor Unicode output.
Checks for Understanding
- How do you pretty-print JSON?
- How can you serialize a datetime?
Show answers
- Use indentinjson.dumps/dump.
- Provide a defaultfunction that returns a serializable representation.
Exercises
- Write a program that reads a JSON file and prints a report of keys and value types.
- Serialize a list of user objects, excluding private fields.