Nested JSON Structures
Navigate and extract values from deeply nested JSON data
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Nested JSON
Real-world JSON is rarely flat. API responses often have objects nested inside objects, with arrays containing more objects.
{
"data": {
"user": {
"name": "Alice"
},
"items": [
{"id": 1, "product": "Laptop"}
]
}
}Navigating nested structures
Chain dictionary lookups with [] to reach nested values. Each [] goes one level deeper.
response["data"]["user"]["name"] # → "Alice"
response["data"]["items"][0]["product"] # → "Laptop"Read left to right: start at response, go into "data", then "user", then "name".
Accessing list items in nested JSON
Use a numeric index to access a specific item in a nested list.
items = response["data"]["items"]
print(len(items)) # number of items
print(items[0]["product"]) # first item's product
Instructions
Extract values from a nested API response.
- Import
json. - Open
api_response.jsonin read mode. Assignjson.load(file)toresponse. - Assign
response["data"]["user"]["name"]touser_name. Callprint(user_name). - Assign
response["data"]["items"][0]["product"]tofirst_item. Callprint(first_item). - Call
print(len(response["data"]["items"]))to print the total number of items.
# api_response.json contains:
# {
# "status": "ok",
# "data": {
# "user": {"name": "Alice", "email": "alice@example.com"},
# "items": [
# {"id": 1, "product": "Laptop", "price": 999.99},
# {"id": 2, "product": "Mouse", "price": 29.99}
# ]
# }
# }
# Step 1: Import json
# Step 2: Open api_response.json and load it into response
# Step 3: Extract the user's name and print it
# Step 4: Extract the first item's product name and print it
# Step 5: Print the total number of items
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding