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=False for Unicode output.

Checks for Understanding

  1. How do you pretty-print JSON?
  2. How can you serialize a datetime?
Show answers
  1. Use indent in json.dumps/dump.
  2. Provide a default function that returns a serializable representation.

Exercises

  1. Write a program that reads a JSON file and prints a report of keys and value types.
  2. Serialize a list of user objects, excluding private fields.