Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท JSON

Working with Nested JSON

Navigate deep JSON safely with optional chaining and destructuring, reshape API results with map, filter and reduce, read NDJSON, and keep payloads fast.

Real API responses are rarely flat. A single order might contain a customer object, an array of line items, and each item may carry its own product details, tags and discounts. Your job as a front-end developer is to turn that tree into whatever the page needs: a list, a total, a grouped summary. Doing that safely, when some branches might be missing, is most of what "working with JSON" means in practice.

This lesson assumes you can already parse and stringify JSON. We will walk through deep structures, protect against missing data, reshape arrays with map, filter and reduce, read the line-oriented NDJSON format, and look at what makes a JSON payload expensive.

All data below is written inline, exactly as if it had come back from a server, so every example runs in the editor.

Reading a nested structure

Here is a typical response. Study its shape before writing any code: an object at the top, arrays inside, objects inside the arrays.

flowchart TD
  R["response"] --> C["customer"]
  R --> I["items (array)"]
  C --> CA["address"]
  I --> I1["item 0"]
  I --> I2["item 1"]
  I1 --> P1["product"]
  I2 --> P2["product"]

A JSON document is a tree: objects and arrays nest to any depth.

You reach into a tree with a path: dots for object keys, square brackets for array positions.

JS Walking a path

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each step must exist, or JavaScript throws. order.items[5].product.name fails with a TypeError because order.items[5] is undefined and you cannot read product from undefined.

Optional chaining and defaults

APIs omit fields all the time: a customer without a phone number, an item without a discount, an error response with no data key. The optional chaining operator ?. stops the path as soon as something is null or undefined and returns undefined instead of throwing. Combine it with ?? (nullish coalescing) to supply a default. See ?. in the reference for the full rules.

JS Optional chaining with defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the last line. ?? only replaces null and undefined, so a legitimate 0 survives. The older || default would wrongly replace it with 5. Prefer ?? for defaults on data you receive.

Optional chaining hides missing data; it does not validate it. If a field being absent is a bug (an order without an id), failing loudly is better than silently printing "unknown". We return to this in Validating JSON Data.

Destructuring to pull out what you need

Destructuring unpacks values into variables in one statement, and it follows the shape of the data. You can rename, set defaults and go several levels deep. The destructuring lesson covers the syntax; here is how it pays off with JSON.

JavaScript
const {
  id,
  customer: { name, address: { city = 'n/a' } = {} },
  items: [firstItem],
} = order;

The = {} after address is a default for the whole branch: if address is missing, destructuring continues with an empty object instead of throwing. It also works in function parameters, which keeps loops tidy:

JS Destructuring in a loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Querying JSON with paths

Destructuring is great when you know the shape in advance. Sometimes you do not: you need "every price in this document" or "the third tag of the first item, if it exists". A path expression names a location inside a JSON document as a string. Several path languages exist:

Language Example Where you meet it
JSONPath (RFC 9535) $.store.book[*].author libraries, API gateways, test tools
JSON Pointer (RFC 6901) /store/book/0/author JSON Patch, JSON Schema $ref
jq filters .store.book[] | .author the command-line jq tool
Plain JavaScript data.store.book.map(b => b.author) everywhere

In JSONPath, $ is the root, .name or ['name'] a child, [0] an index, [*] every child, .. searches at any depth and [?(@.price < 10)] filters. In jq you write .store.book[] | select(.price < 10) | .title in a terminal, which is handy for exploring an API response saved to a file.

In browser code you rarely need a full library. Two small helpers cover most cases. The first, a safe deep get, reads a dotted path with a default and never throws. The second is a tiny JSONPath-style evaluator for the common forms, so you can see how such engines work.

JS Safe deep get and a mini JSONPath

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line shows the honest answer to "do I need JSONPath?": for data your own code owns, filter and map are clearer and type-checkable. JSONPath earns its place when the query comes from outside your code (a configuration file, a test script, an API gateway rule), because a string can be stored and changed without redeploying. Use a maintained library for that case rather than the toy evaluator above; it ignores many details of the standard, such as slices, unions and escaping.

For quick exploration, paste a response into the browser console and use copy(JSON.stringify(data, null, 2)) to format it, or save it and try jq on the command line. And remember optional chaining, which is the built-in path syntax of JavaScript.

Reshaping arrays: map, filter, reduce

Most API data arrives as an array of records. Three methods do nearly all the reshaping:

  • map turns each record into something else (often a smaller object for display).
  • filter keeps only the records that match.
  • reduce folds the array into one value: a total, a lookup table, groups.
JS Totals, filters and groups

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The ??= line creates the group array the first time a category appears. The last pattern, turning an array into an object keyed by id, is worth memorizing: looking up bySku['D-900'] is instant, while lines.find(...) scans the list every time.

Flattening nested arrays

When each parent holds an array of children, flatMap maps and flattens one level in one step:

JavaScript
const orders = [
  { id: 1, items: [{ sku: 'A' }, { sku: 'B' }] },
  { id: 2, items: [{ sku: 'C' }] },
];
const allSkus = orders.flatMap((order) => order.items.map((item) => item.sku));
// ["A", "B", "C"]

NDJSON: one JSON value per line

A JSON array must be complete before you can parse it: one missing bracket at the end and nothing works. When a server wants to send thousands of records, or keep sending them for a long time, it often uses NDJSON (newline-delimited JSON, also called JSON Lines). Each line is a complete JSON value; lines are separated by \n.

Text
{"id":1,"level":"info","msg":"started"}
{"id":2,"level":"warn","msg":"slow disk"}
{"id":3,"level":"error","msg":"crashed"}

You parse it by splitting on newlines and parsing every line on its own. That means one bad line does not ruin the rest, and a stream can be processed line by line while it is still arriving (see Streaming and Real-Time APIs).

JS Parsing NDJSON

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the broken fourth line is reported but the fifth is still read. With a single big array, that one typo would have cost you every record.

Size and performance

JSON is text, and text has a cost: the network transfers it, then JSON.parse turns it into objects on the main thread. A few habits keep this cheap.

  • Ask for less. Use query parameters such as fields=id,name or pagination (see Web APIs and REST in Practice) instead of downloading everything.
  • Compression (gzip or Brotli) is applied by the server and browser automatically and often shrinks JSON by 80% or more, because the repeated key names compress well.
  • Do not stringify to compare or clone big data in hot loops. JSON.stringify and JSON.parse walk the whole tree each time. Use structuredClone for deep copies (see Revivers, Replacers and toJSON).
  • Parse once. Store the parsed result and reuse it rather than re-parsing the same string.
  • Very large payloads (many megabytes) block the page while parsing. Paginate, stream as NDJSON, or parse inside a Web Worker.
JS Measuring a payload

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Pretty-printing is for humans. Send compact JSON over the wire and indent only for logs and debugging.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does order.customer.address?.city return when address is missing?

    Optional chaining stops at the first null or undefined and the whole expression evaluates to undefined instead of throwing.
  2. 2. Why prefer ?? over || when supplying a default for API data?

    || replaces every falsy value, including 0, false and empty strings, which are often legitimate data.
  3. 3. What is the main advantage of NDJSON over one big JSON array?

    Every line is a complete JSON value. You can parse lines independently and start work before the whole response has arrived.
  4. 4. Which approach gives you the fastest repeated lookups of records by id?

    Indexing once with Object.fromEntries (or a Map) makes each later lookup a direct key access instead of a scan of the list.

Summary

  • A JSON document is a tree; reach into it with dotted paths and array indexes.
  • Use ?. to avoid crashes on missing branches and ?? for defaults that keep 0 and "".
  • Destructure nested data, with defaults such as = {}, to pull out only what you need.
  • map, filter, reduce, flatMap and Object.groupBy reshape API results; index records by key for fast lookups.
  • NDJSON puts one JSON value per line, so lines parse independently and can stream.
  • Ask the server for less, send compact JSON, parse once, and move huge parsing off the main thread.

Next: Validating JSON Data.