Lesson 9
JSONPath Queries
Extract values from nested documents using path expressions.
When a JSON document is large, you often need one field without mentally traversing every level. JSONPath is a query language—similar in spirit to XPath for XML—for selecting nodes in JSON trees.
Sample document
{
"store": {
"books": [
{ "title": "JSON 101", "price": 12.5 },
{ "title": "API Design", "price": 28 }
]
}
}
Common expressions
| Expression | Meaning |
|---|---|
$ | Root of the document |
$.store.books | The books array |
$.store.books[0].title | Title of first book |
$.store.books[*].price | All prices |
$..price | price anywhere under root |
Read $ as “start here,” . as “child property,” [n] as array index, [*] as every element, and .. as recursive descent.
Use cases
- Pull a user ID from a nested API response in tests or scripts
- Filter log events where
level == "error"across heterogeneous payloads - Document “where to find” fields in integration guides
JSONPath vs manual code
In JavaScript you might write data.store.books[0].title. JSONPath shines when:
- Depth varies between API versions
- You query the same path in config across many files
- Tools expose a path box for ad-hoc inspection
Limitations
Implementations differ slightly on extensions (filters, slices). For production pipelines, pin a library version and add tests for critical paths. JSONPath reads structure—it does not fix invalid JSON; parse and validate first.