Lesson 5 of 12 · Data on the Wire
JSON
Learn JSON, the data format almost every API uses: objects, arrays, how JSON maps to Python, json.loads and json.dumps, and how to read nested API responses safely.
- 8 min read
- Beginner
- Reviewed
- What JSON is and why APIs use it
- How JSON objects and arrays match Python dictionaries and lists
- How to turn JSON text into Python data and back
- How to dig into nested API responses safely
The shared language for data
A server might be written in Java, and your client in Python. They need a way to send data that both can read. Almost every web API uses the same simple text format for this: JSON.
Here is a small piece of JSON, describing a user:
{
"name": "Ada",
"age": 36,
"is_admin": false,
"skills": ["Python", "SQL"],
"manager": null
}If you have used Python dictionaries, this looks very familiar.
Objects and arrays
JSON is built from just two kinds of container.
The values inside can be text, numbers, true, false, null, or more objects and arrays. Here is how each one maps to Python:
| JSON | Python | Example |
|---|---|---|
| object | dict | {"name": "Ada"} |
| array | list | [1, 2, 3] |
| string | str | "hello" |
| number | int or float | 36, 28.5 |
true / false | True / False | note the lowercase in JSON |
null | None | a missing value |
Two strict rules: JSON text must use double quotes, never single quotes, and it does not allow a comma after the last item.
From JSON text to Python: parsing
The body of an API response arrives as text. Parse it, and you can use it like any dictionary:
import json
body = '{"name": "Ada", "age": 36, "is_admin": false, "skills": ["Python", "SQL"], "manager": null}'
user = json.loads(body)
print(type(body).__name__, "->", type(user).__name__)
print(user["name"], "is", user["age"])
print("Admin?", user["is_admin"])
print("First skill:", user["skills"][0])
print("Manager:", user["manager"])Look at the output: false became False, and null became None. The s in loads stands for string: load from a string.
From Python to JSON text: serialising
When you send data to an API, such as a new post or a message for an AI model, it must be turned into JSON text first:
import json
message = {
"model": "example-model",
"messages": [{"role": "user", "content": "What is an API?"}],
"stream": False,
}
text = json.dumps(message)
print(text)
print()
print(json.dumps(message, indent=2))indent=2 makes the JSON easier for people to read. Notice that False became false again. The requests library calls json.dumps() for you when you pass json=..., and response.json() calls json.loads() for you.
Reading nested data
Real responses are nested: objects inside objects, inside arrays. Read them one step at a time, from the outside in.
import json
body = """
{
"city": "Hyderabad",
"current": {"temperature": 28.5, "wind_speed": 12.0},
"daily": [
{"date": "2026-11-17", "max": 29.9, "min": 20.2},
{"date": "2026-11-18", "max": 29.5, "min": 21.3}
]
}
"""
data = json.loads(body)
print(data["current"]["temperature"]) # object inside an object
print(data["daily"][1]["max"]) # object inside an array
for day in data["daily"]:
print(day["date"], "max", day["max"], "min", day["min"])A good habit: when a response looks confusing, print it with json.dumps(data, indent=2) and read the shape before writing any code.
Missing keys
APIs sometimes leave out a field. Using [] on a missing key crashes the program with a KeyError. The .get() method returns None, or a default you choose, instead:
import json
user = json.loads('{"name": "Grace", "email": "[email protected]"}')
print(user.get("email"))
print(user.get("phone"))
print(user.get("phone", "no phone given"))Use [] for fields that must always be there, and .get() for optional ones.
JSON from a real API
import requests
response = requests.get("https://jsonplaceholder.typicode.com/users/1", timeout=10)
user = response.json()
print("Name: ", user["name"])
print("Email: ", user["email"])
print("City: ", user["address"]["city"])
print("Company:", user["company"]["name"])
print("Fields: ", list(user.keys()))Common mistakes
Parse a JSON response that holds a list of users, then filter it.
import json
body = """
[
{"name": "Ada", "city": "London", "active": true},
{"name": "Ravi", "city": "Hyderabad", "active": true},
{"name": "Mei", "city": "Hyderabad", "active": false},
{"name": "Sara", "city": "Hyderabad", "active": true}
]
"""
# 1. Parse the JSON text.
# 2. Print the name of every ACTIVE user in Hyderabad.
# 3. Then print how many users there are in total.
# Output must be exactly:
# Ravi
# Sara
# Total users: 4
What does the JSON value null become after json.loads()?
Summary
- JSON is the text format almost every API uses for data.
- A JSON object becomes a dictionary and a JSON array becomes a list.
true,falseandnullbecomeTrue,FalseandNone. json.loads()parses JSON text.json.dumps()serialises Python data into JSON text.- Read nested data step by step, and use
.get()for fields that might be missing.
Next: headers, the extra information that travels with every request and response.
Finished reading? Tick it off to track your progress.