APIs and Async · HTTP and JSON · lesson 3 of 12
Parsing JSON safely
about 14 minutes · free · runs in your browser
Do not trust the shape
response.json() gives you whatever the server sent. Reaching straight into it with
square brackets assumes every key is present and every field is the type you expect,
which is how a client breaks at three in the morning when an API adds a null.
Defensive reading is short and worth it:
data = response.json()
name = data.get("name", "unknown")
tags = data.get("tags") or [] # handles both missing and null
count = int(data.get("count", 0))
Note or [] rather than a plain default: data.get("tags", []) still returns
None if the key exists with a null value, which is the case that actually bites.
Your turn: write read_user(payload) that copes with missing and null fields,
returning {"name": ..., "team": ..., "tags": [...]} with defaults "unknown",
"none" and [].
You start from this, and edit it in the browser:
def read_user(payload):
# Read defensively: fields may be missing or null.
pass