JSON Nested Data
Real-world JSON is rarely flat. Objects contain arrays, arrays contain objects, and those contain more objects. Learning to navigate nested data confidently is one of the most useful JSON skills.
A nested document
Here's an order from an online shop. Run it to see the full structure:
{
"orderId": "A-2041",
"customer": {
"name": "Thao",
"address": {"city": "Hue", "zip": "530000"}
},
"items": [
{"sku": "TEA-001", "qty": 2, "price": 4.5, "options": {"size": "large"}},
{"sku": "MUG-010", "qty": 1, "price": 9.0, "options": {}}
],
"payments": [
{"method": "card", "amount": 18.0}
]
}Valid JSON: object with 4 keys
{
"orderId": "A-2041",
"customer": {
"name": "Thao",
"address": {
"city": "Hue",
"zip": "530000"
}
},
"items": [
{
"sku": "TEA-001",
"qty": 2,
"price": 4.5,
"options": {
"size": "large"
}
},
{
"sku": "MUG-010",
"qty": 1,
"price": 9,
"options": {}
}
],
"payments": [
{
"method": "card",
"amount": 18
}
]
}
Building a path
To reach a value, chain property names (for objects) and indexes (for arrays) from the outside in:
| Path in JavaScript | Value |
|---|---|
order.orderId |
"A-2041" |
order.customer.address.city |
"Hue" |
order.items[0].sku |
"TEA-001" |
order.items[1].qty |
1 |
order.items[0].options.size |
"large" |
order.payments.length |
1 |
const order = JSON.parse(`{
"orderId": "A-2041",
"customer": {"name": "Thao", "address": {"city": "Hue", "zip": "530000"}},
"items": [
{"sku": "TEA-001", "qty": 2, "price": 4.5, "options": {"size": "large"}},
{"sku": "MUG-010", "qty": 1, "price": 9.0, "options": {}}
],
"payments": [{"method": "card", "amount": 18.0}]
}`);
console.log(order.customer.address.city);
console.log(order.items[0].options.size);
const total = order.items.reduce((sum, it) => sum + it.qty * it.price, 0);
console.log("Total:", total);
for (const it of order.items) {
console.log(`${it.sku} x${it.qty}`);
}Hue
large
Total: 18
TEA-001 x2
MUG-010 x1
Missing data and optional chaining
If any step in a path is missing, the next step throws a TypeError. The optional chaining operator ?. stops early and returns undefined instead, and ?? supplies a default:
const users = JSON.parse(`[
{"name": "An", "profile": {"social": {"github": "an-dev"}}},
{"name": "Bao", "profile": {}},
{"name": "Cuc"}
]`);
for (const u of users) {
const gh = u.profile?.social?.github ?? "(none)";
console.log(u.name, gh);
}
try {
console.log(users[2].profile.social);
} catch (err) {
console.log(err.name);
}An an-dev
Bao (none)
Cuc (none)
TypeError
Updating nested values
You change nested values the same way you read them:
const config = JSON.parse('{"server": {"port": 8080, "tls": {"enabled": false}}, "features": ["search"]}');
config.server.port = 443;
config.server.tls.enabled = true;
config.server.tls.cert = "/etc/certs/site.pem";
config.features.push("export");
console.log(JSON.stringify(config, null, 2));{
"server": {
"port": 443,
"tls": {
"enabled": true,
"cert": "/etc/certs/site.pem"
}
},
"features": [
"search",
"export"
]
}
Walking an unknown structure
Sometimes you don't know the shape in advance. A small recursive function can visit every value and print its path:
function walk(value, path = "quot;) {
if (Array.isArray(value)) {
value.forEach((v, i) => walk(v, `${path}[${i}]`));
} else if (value !== null && typeof value === "object") {
for (const [k, v] of Object.entries(value)) walk(v, `${path}.${k}`);
} else {
console.log(path, "=", JSON.stringify(value));
}
}
walk(JSON.parse('{"a": 1, "b": [true, {"c": null}], "d": {"e": "x"}}'));$.a = 1
$.b[0] = true
$.b[1].c = null
$.d.e = "x"
The $ symbol for "the root" is borrowed from JSONPath, a query syntax for JSON.
Design tips for nested JSON
- Keep nesting shallow. Three or four levels is usually plenty; deeper structures are hard to read and query.
- Be consistent. If
optionsis an object in one item, make it an object (maybe empty) in every item. - Prefer arrays of objects to objects keyed by IDs when order or iteration matters.
- Don't repeat data. Reference related records by ID instead of embedding full copies everywhere.
Test yourself
Given the order above, which expression gives "MUG-010"?
- order.items.1.sku
- order.items[1].sku
- order[items][1][sku]
- order.items.sku[1]
What does obj.a?.b return when obj.a is undefined?
- null
- It throws a TypeError
- undefined
- false