Nested JSON Structures
Exit

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.

  1. Import json.
  2. Open api_response.json in read mode. Assign json.load(file) to response.
  3. Assign response["data"]["user"]["name"] to user_name. Call print(user_name).
  4. Assign response["data"]["items"][0]["product"] to first_item. Call print(first_item).
  5. Call print(len(response["data"]["items"])) to print the total number of items.