How to Use JSONPath to Query JSON
Extract specific values from deeply nested JSON using JSONPath expressions.
Problem
You need to extract specific fields from a large, deeply nested JSON document without writing custom traversal code.
Prerequisites
- Understanding of JSON structure
- Familiarity with path expressions
Steps
-
1. Learn the JSONPath syntax
JSONPath uses dot notation for object keys ($.store.book) and brackets for array indices ([0]) or filters ([?(@.price < 10)]). The $ represents the root. Wildcards (*) match all elements. This is similar to XPath for XML.
Input$.store.book[0].titleOutputfirst book's title -
2. Write and test the expression
Construct the JSONPath expression for the data you want to extract. Test it against your JSON document. Filters use @ to reference the current element. Multiple matches return an array of results.
Input$.store.book[?(@.price<10)].titleOutputtitles of books under $10 -
3. Handle edge cases
Not all JSONPath implementations support the full spec. Filters, recursive descent ($..), and script expressions may vary. Check your implementation's capabilities. Handle missing paths gracefully — they return empty results, not errors.
Input$..authorOutputall authors at any depth
Expected result
The specific values extracted from the JSON document matching the JSONPath expression.
Common errors
- Filter syntax not supported
- Different JSONPath implementations support different filter syntaxes. Check the documentation for your specific implementation.
- Path returns empty unexpectedly
- Verify the path matches the JSON structure. Check for case sensitivity in keys and correct array indices.
Troubleshooting
- If the path returns nothing, print the JSON structure and verify each segment exists.
- Use recursive descent ($..) to find keys at any depth if you are unsure of the exact path.
Security limits
- JSONPath is a read-only query language. It does not modify data or execute code.
- All querying is local.
Related tools
Related glossary
Related tasks
Ready to run it?