Real-world JSON is rarely flat. An order contains a customer, the customer contains an address, and the address contains coordinates. Understanding how objects nest, and how to navigate that nesting safely, is the core skill of working with API responses. In this lesson of our JSON tutorial series, we model realistic data with nested objects and practice reading values out of them.
An object is a set of key and value pairs inside curly braces. Each key is a double-quoted string followed by a colon and a value:
{
"sku": "TSHIRT-M-BLUE",
"price": 19.99,
"inStock": true
}Keys should be unique. Choose a consistent naming convention, with camelCase and snake_case being the two most common in APIs, and stick to it across your entire payload.
Any value can itself be an object, which lets you group related fields:
{
"orderId": "ORD-2091",
"customer": {
"name": "Grace Hopper",
"email": "grace@example.com",
"address": {
"street": "1 Navy Way",
"city": "Arlington",
"geo": { "lat": 38.88, "lng": -77.09 }
}
},
"total": 74.5
}This document nests four levels deep. Each level adds meaning: the geo coordinates belong to the address, the address belongs to the customer, and the customer belongs to the order.
After parsing, you drill into the structure with property access. In JavaScript:
const order = JSON.parse(payload);
console.log(order.customer.address.city); // "Arlington"
console.log(order["customer"]["email"]); // bracket notation also worksThe danger is that any level may be missing. If customer is absent, order.customer.address throws a TypeError. Modern JavaScript solves this with optional chaining: order.customer?.address?.city returns undefined instead of crashing. In Python you would use order.get("customer", {}).get("address", {}).
Most API responses are arrays of objects, or objects that contain arrays of objects:
{
"items": [
{ "sku": "PEN-01", "qty": 3 },
{ "sku": "NOTEBOOK-A5", "qty": 1 }
]
}To total the quantities you iterate the array and read each object, a pattern you will use daily.
Nesting mirrors real relationships, but excessive depth makes documents hard to read and code hard to write. As a rule of thumb, keep payloads within three or four levels. If you find yourself six levels deep, consider flattening, for example replacing a nested chain with a top-level shippingCity field, or splitting the resource into separate API endpoints.
Next up: JSON Arrays, a deep dive into ordered data, iteration, and common array patterns.