04 / FILES AND FORMATS · LESSON 15

JSON for nested configuration

Load typed configuration and write a structured summary.

12 min · learn at your pace

JSON keeps structure and simple types

JSON represents dictionaries, lists, strings, numbers, Booleans, and null. json.load(file) reads a document; json.loads(text) parses a string. Python maps JSON true, false, and null to True, False, and None.

Unlike CSV, a JSON number is already numeric after parsing. Use the documented schema to decide which fields are required and what their types should be. A parseable document can still have invalid application data. The capstone will validate its policy before using it.

Write data that another program can read

Use json.dump(value, file, indent=2) for readable output. ensure_ascii=False keeps Unicode readable while the file remains UTF-8. Do not build JSON by joining strings: embedded quotes and backslashes need escaping.

Lists retain their order; object key order should not determine the meaning of a document. The exercise checks parsed values, not indentation or key ordering, so several formatting choices can pass. Keep machine-readable numbers and Booleans as their original types rather than converting everything into display text.

Try an example.py
import json
from pathlib import Path
policy = json.loads(Path("assets/policy.json").read_text(encoding="utf-8"))
print(policy["minimum_memory_gb"], policy["sites"])
YOUR TURN

Put it into practice.

Read assets/policy.json. Create output/policy-summary.json containing minimum_memory_gb (the original number), enabled (the original Boolean), and site_count (the number of sites). Keep JSON types intact.

See an explained solution
One way to solve it.py
import json
from pathlib import Path
policy = json.loads(Path("assets/policy.json").read_text(encoding="utf-8"))
summary = {"minimum_memory_gb": policy["minimum_memory_gb"], "enabled": policy["enabled"], "site_count": len(policy["sites"])}
Path("output").mkdir(exist_ok=True)
Path("output/policy-summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")

Parsing gives a dictionary with typed values. The new dictionary selects just the contract’s three fields, and json.dumps handles valid JSON encoding.