Part 12 / Topic 5 of 11
Working with JSON responses
After json.load, an API answer is just dicts and lists (Part 4), often nested (a dict inside a dict inside a list). Real answers are messy: some keys are missing, some values are null (which becomes None).
Think of a filled-in form where some boxes are empty: read what is there and use a sensible default for the rest.
| Situation | Code | Why |
|---|---|---|
| Key must exist | order["customer"]["name"] |
A KeyError tells you the data is broken |
| Key may be missing | item.get("qty", 1) |
Default when missing |
Value may be null |
order.get("delivery") or {} |
.get returns None for null; or turns it into {} |
| Missing nested dict | data.get("address", {}).get("city", "unknown") |
Each step has a safe default |
import json
text = """{"order_id": "ORD-1042",
"customer": {"name": "Priya Nair", "address": {"city": "Kochi"}},
"items": [{"name": "Bottle", "price": 450, "qty": 2},
{"name": "Lamp", "price": 650}],
"delivery": null}"""
order = json.loads(text)
print(order["customer"]["address"]["city"]) # Kochi
print(order["customer"].get("phone", "not given")) # not given
print(order.get("delivery")) # None
print((order.get("delivery") or {}).get("courier", "not assigned")) # not assigned
print(sum(i["price"] * i.get("qty", 1) for i in order["items"])) # 1550
From API data to dataclasses
Dicts with string keys are easy to mistype (item["prcie"]). Turn them into dataclasses (Part 9) once, at the edge of your program. After that you get real attributes, a nice repr, and your editor can help you.
from dataclasses import dataclass
@dataclass
class DayForecast:
day: str
max_c: float
rain_mm: float
daily = { # Open-Meteo sends one list per field
"time": ["2026-07-01", "2026-07-02"],
"temperature_2m_max": [29.4, 28.1],
"precipitation_sum": [12.5, 30.2],
}
days = [
DayForecast(day, max_c, rain)
for day, max_c, rain in zip( # zip joins the lists day by day
daily["time"], daily["temperature_2m_max"], daily["precipitation_sum"]
)
]
print(days[0]) # DayForecast(day='2026-07-01', max_c=29.4, rain_mm=12.5)
print(max(days, key=lambda d: d.rain_mm).day) # 2026-07-02
Full program: examples/03_json_to_dataclasses.py (reads sample_order.json and sample_weather.json).
Done here? The practice set for Part 12 — 8 exercises with solutions — is on the part page.