How to Read Nested JSON and API Responses
Real API responses are rarely flat. The value you need is usually several levels down: inside an object, inside an array, inside another object. This guide shows you how to read that structure, write the exact path to any value, and avoid the errors that come from getting a path slightly wrong.
An example API response
Imagine you've called an online store's API to get a customer's recent orders. It returns this:
{
"status": "ok",
"data": {
"customer": {
"id": "c_381",
"name": "Maria Garcia",
"email": "maria@example.com"
},
"orders": [
{
"id": 5001,
"total": 42.5,
"items": [
{ "sku": "MUG-01", "name": "Coffee mug", "qty": 2 },
{ "sku": "TEA-12", "name": "Green tea", "qty": 1 }
]
},
{
"id": 5002,
"total": 18,
"items": [{ "sku": "PEN-03", "name": "Gel pen", "qty": 6 }]
}
]
},
"meta": { "page": 1, "pageSize": 20, "totalOrders": 2 }
}Open this response in the JSON tool and explore it as a tree
Suppose you need the name of the second item in the first order ("Green tea"). Before writing any code, work out where it sits.
Step 1: map the structure
JSON is built from two containers, and telling them apart is the whole skill:
- Objects, in curly braces
{ }, hold named values. You reach inside with a key:customer,email. - Arrays, in square brackets
[ ], hold an ordered list. You reach inside with a position number, starting from 0.
Read the response from the outside in, noting the container at each level:
- The whole response is an object with three keys:
status,dataandmeta. datais an object with two keys:customerandorders.ordersis an array of 2 orders. The first is at position 0.- Each order is an object. Its
itemskey holds another array. - Each item is an object with
sku,nameandqty.
In the JSON tool's explore view, objects are drawn as rounded blue boxes and arrays as square green boxes, each labelled with how many keys or items it holds. Collapsing the boxes you don't need is the fastest way to see this outline in a large response.
Step 2: write the path
A path is the list of keys and positions you follow from the top to the value. Write it by joining each step: a dot and the name for an object key, and the position in square brackets for an array.
const response = await res.json();
response.data.orders[0].items[1].name // "Green tea"
response.data.customer.email // "maria@example.com"
response.data.orders[1].total // 18
response.meta.totalOrders // 2Reading the first path aloud helps: "In the response, go into data, then orders, take the item at position 0, go into its items, take position 1, and read its name."
Positions start at 0
The first element of an array is [0], the second is [1], and the last is [array.length - 1]. Off-by-one mistakes here are one of the most common reasons a path returns the wrong value or undefined.
Dot notation only works when the key is a valid identifier: letters, digits, _ and $, not starting with a digit. For any other key, use square brackets with the key in quotes:
data["first-name"] // key contains a hyphen
data["2024"] // key starts with a digit
data["Content-Type"] // common in HTTP headers
data[fieldName] // key stored in a variableWorking with arrays of objects
Hard-coding [0] only works when you want one specific element. Most of the time you want to do something with every element, and arrays of objects are where JSON meets loops. Using the response above:
const orders = response.data.orders;
// Every order ID
const ids = orders.map((order) => order.id); // [5001, 5002]
// Find one order by a value, not by position
const order = orders.find((o) => o.id === 5002); // the second order
// Arrays inside arrays: every item name across all orders
const names = orders.flatMap((o) => o.items.map((i) => i.name));
// ["Coffee mug", "Green tea", "Gel pen"]
// Add up a value
const spent = orders.reduce((sum, o) => sum + o.total, 0); // 60.5Prefer find over a fixed position when you're looking for a particular record. APIs don't always promise an order, and the order you want might not stay at position 0.
"Cannot read properties of undefined"
This is the error you'll see most when a path is wrong. In Chrome and Node it looks like this:
TypeError: Cannot read properties of undefined (reading 'name')It means the step before .name gave undefined. Reading a missing key isn't an error by itself, but going one step further into it is. So for response.data.costumer.name, the real mistake is the typo costumer instead of customer, even though the message mentions name. With an array it names the position instead: a typo in response.data.order[0] gives (reading '0').
To track it down, log each step of the path until one is undefined:
console.log(response.data); // object: fine
console.log(response.data.costumer); // undefined: found it (should be "customer")Some data is legitimately optional, like a customer without a phone number. For those fields, optional chaining (?.) stops at the first missing step and returns undefined instead of throwing, and ?? supplies a default:
const phone = response.data.customer?.phone ?? "No phone on file";
const firstItem = response.data.orders?.[0]?.items?.[0]?.name;Use optional chaining for fields that really can be missing. Sprinkling it everywhere hides genuine mistakes like the costumer typo above.
The same paths in Python and jq
Paths work the same way in other languages. Only the punctuation changes. In Python, every step uses square brackets, and .get() plays the role of optional chaining:
import json
response = json.loads(text)
response["data"]["orders"][0]["items"][1]["name"] # "Green tea"
response["data"]["customer"].get("phone", "No phone on file")
names = [item["name"] for order in response["data"]["orders"] for item in order["items"]]On the command line, jq uses a path syntax very close to JavaScript's, which makes it great for poking at API responses with curl:
jq '.data.orders[0].items[1].name' response.json # "Green tea"
jq '.data.orders[].id' response.json # 5001 and 5002, one per line
jq '[.data.orders[].items[].name]' response.json # all item names as an arrayTips for large responses
- Look at the shape before the data. Collapse everything, then open one level at a time. Item counts on each box tell you where the big lists are.
- Check one element of a long array. If an array has 500 orders, they almost always share a structure. Understand the first and you understand them all.
- Watch for wrapper objects. Many APIs put the real data under a key like
data,resultsoritems, next to metadata such as page numbers. Forgetting that first step is a very common source ofundefined. - Don't assume a type. An ID might be a number in one API (
5001) and a string in another ("c_381"), and5001 === "5001"is false in JavaScript. - Read the API docs alongside the response. The docs tell you which fields are optional and which can be
null, which one example response can't show.