JSONPath in Practice: Pinpointing Values in Nested JSON

A Real Extraction Request

A deeply nested order response, and you need "order ids with status paid plus their totals". In code that is a loop plus a condition plus a collector; with JSONPath it is one line per field:

$.orders[?(@.status=="paid")].id
$.orders[?(@.status=="paid")].total

Classic JSONPath projects one field per expression, so two fields take two expressions; what it removes is the traversal, filter and projection work, not the merging of results.

{
  "orders": [
    { "id": "o1001", "status": "paid",     "total": 128.5 },
    { "id": "o1002", "status": "pending",  "total": 59.0  },
    { "id": "o1003", "status": "paid",     "items": [
        { "sku": "A-01", "price": 39.9 },
        { "sku": "A-02", "price": 20.1 }
      ], "total": 60.0 }
  ]
}

Syntax Quick Reference

Expression Meaning Returns
$ root node the whole document
.key / ['key'] child property that property
* wildcard all children / elements
..key recursive descent matching keys at any depth
[0] array index that element
[0,2] multiple indexes elements 0 and 2
[start:end] slice the range
[?(@.k==v)] filter elements matching the condition

Segment by Segment

$                      → the whole object
$.orders[1].id         → "o1002"
$.orders[*].id         → ["o1001","o1002","o1003"]
$.orders[?(@.total>60)].id
                       → ["o1001","o1003"]
$..price                → [39.9,20.1]       (collect every price recursively)

..price also digs out the price nested inside items—the value of recursive descent. The cost is a depth-first walk of the whole tree: slower than a targeted path on large documents, with results in traversal order that may not match the ordering you expect across objects.

$ and @

$ always starts from the root, and $.a.b.c is an explicit path; @ means "the element being visited" only inside a filter. Combining them gives "filter a subset by condition, then take a field inside it":

$.orders[?(@.status=="paid" && @.total>=60)].id
$..[?(@.status=="paid")]                 # filter paid at any depth

The second attaches a filter to recursive descent, which again walks the whole tree—use it only when the depth is genuinely unknown. When you know the depth, write the full path: faster and more readable.

Empty Result or Error

The syntax does not check whether a key exists; two outcomes must be told apart:

  • Returns []: the path is valid and nothing matched. An empty $..price only means no price key exists anywhere, not that the path is wrong.
  • Throws: the path itself is illegal, e.g. an index applied to a non-array, or unclosed brackets.

Debug coarse to fine: use $[*] to list top-level keys, then extend the path segment by segment—the level where it turns empty is the break. Formatting first makes hierarchy readable, better than counting braces in minified text (JSON formatter); tune expressions against real data in the JSONPath finder.

A Practical Workflow

When debugging a third-party API, my extraction order is:

  1. Format the response and look at the overall levels;
  2. Use a coarse wildcard such as $[*] to confirm field-name spelling;
  3. Land on an exact path or filter expression;
  4. Cross-check: run the same path against two response versions and see what changed (with JSON Diff).

Reproducible Results

The semantics of $.store.book[?(@.price<10)].title, derived once in Python:

data = {"store": {"book": [{"title": "A", "price": 8}, {"title": "B", "price": 12}]}}
books = data["store"]["book"]
print([b["title"] for b in books if b["price"] < 10])   # → ['A']

Reading side by side: $ = the whole data; .store.book = two subscripts; [?(@.price<10)] = the if in the comprehension; the final .title = projection. JSONPath has no power beyond these four operations, and any complex expression decomposes into them.

Frequently Asked Questions

What is the difference between JSONPath and JSON Pointer?

JSONPath is a query language closer to SQL/regex: it supports wildcards (*), recursive descent (..), array indexes and filter expressions ([?(@.age>18)]), returning a set of matched nodes—great for mining nested JSON. JSON Pointer is a strict locator like /a/b/0 that points to one exact predetermined node with no wildcards or filters; it is mainly used by JSON Patch and error reporting. In short: use JSONPath to query, JSON Pointer to locate.

What exactly does recursive descent .. do?

..name means 'depth-first traverse the whole document and collect every key named name regardless of depth'. It is ideal when you don't care how deeply a field is nested and just want all prices or IDs. The trade-off: results come back in traversal order (possibly unordered across objects) and it is slower than a targeted path on large JSON. When you know the exact depth, prefer a full path ($.a.b.c); use recursive descent when nesting is unknown.

What does @ mean inside a filter like [?(@...)]?

Inside a filter expression, @ refers to the current array element being visited. $.users[?(@.age > 30)].name runs the filter over each element (where @ is that element), keeps those with @.age>30, then projects their name. ? marks a filter and (...) holds a boolean condition, supporting comparisons, logical &&/||, and field-existence checks like @.field. This screening power is where JSONPath separates from plain path extraction.

← Back to Blog