Parse Nested JSON in JavaScript: Objects, Arrays, and Safe Access
Nested JSON is just JSON with objects inside objects or arrays inside objects. The hard part is usually not parsing it with JSON.parse(), but safely reading deep values after the parse succeeds.
Parse nested JSON into a JavaScript object
const raw = '{"user":{"profile":{"name":"Alice","age":31}},"roles":["admin","editor"]}'
const data = JSON.parse(raw)
console.log(data.user.profile.name)
console.log(data.roles[1])If you need the base parsing pattern first, start with JSON to JavaScript object.
Access deep properties safely
Real payloads often omit optional branches. Optional chaining prevents crashes when a nested property is missing.
const city = data.user?.profile?.address?.city ?? 'Unknown'
const firstRole = data.roles?.[0] ?? 'guest'Loop through arrays inside nested JSON
Nested arrays are common in API payloads. Parse once, then iterate like normal JavaScript data.
const raw = '{"orders":[{"id":1,"items":[{"sku":"A1"},{"sku":"B2"}]}]}'
const payload = JSON.parse(raw)
for (const order of payload.orders) {
for (const item of order.items) {
console.log(item.sku)
}
}Handle nested JSON parse errors
A nested payload still fails the same way as any other invalid JSON string. Put the parse intry/catch, then inspect the structure only if parsing succeeded.
try {
const payload = JSON.parse(raw)
console.log(payload.user?.profile?.name)
} catch (error) {
console.error('Invalid JSON', error)
}If the issue is malformed input, see JSON.parse error JavaScript.
Validate nested data shape
Parsing only proves syntax. Nested APIs often need stronger checks for required arrays, objects, and field types.
if (!Array.isArray(payload.orders)) {
throw new Error('orders must be an array')
}
if (typeof payload.user?.profile?.name !== 'string') {
throw new Error('user.profile.name must be a string')
}For reusable deep validation rules, use JSON Schema examples.
Inspect nested JSON before coding against it
Use Jsonic's JSON Formatter to pretty print deep structures or the JSONPath Tester to query nested fields quickly.