What is JSONPath and how does it compare to XPath?
JSONPath is a query language for selecting nodes inside a JSON document, designed to feel like XPath but adapted for JSON. The dollar sign represents the root, dots traverse keys, and brackets access array indices or apply filters. It is widely used in API testing tools, log pipelines, and JSON-aware databases for plucking values out of large documents without writing custom parsing code.
What do the wildcard, recursive, and slice operators do?
The asterisk wildcard matches every direct child key or array index. Two dots traverse recursively into every descendant, useful for finding a key anywhere in a deeply nested document. Slice notation like [0:5] selects a range of array elements with optional step. Combining them - for example $..book[*].title - extracts every book title regardless of nesting depth.
How do filter expressions work in JSONPath?
Filters use the syntax [?(...)] where the expression inside is evaluated for each candidate node. Inside the filter, the at-sign refers to the current item, so [?(@.price < 10)] keeps only items whose price is below ten. You can chain comparisons, use logical and/or, and call functions like length. Filters are the most powerful feature for extracting subsets without external code.
Why does my JSONPath query return nothing?
The most common causes are case-sensitive key names, an off-by-one array index, a missing root dollar sign, or a filter expression that compares a string to a number. Step through the path piece by piece - start with the root, add one segment at a time, and confirm you get a non-empty result before continuing. The path syntax is unforgiving but predictable.
Are there differences between JSONPath implementations?
Yes. The original Goessner spec is informal, so libraries diverge on script expressions, filter syntax, and how recursive descent interacts with arrays. The newer RFC 9535 standardizes the language, but adoption varies. When portability matters, stick to the common subset - root, dot, brackets, wildcard, recursive descent, and basic filters - and avoid script expressions that wrap arbitrary code.
When should I use JSONPath versus jq?
JSONPath is great for selection and filtering with a compact syntax, especially when integrated into other tools that already support it. Jq is a fuller programming language with transformation, reduction, and string manipulation, making it a better fit for complex pipelines. Pick JSONPath for read-only extraction and jq when you need to reshape, aggregate, or compute on the data after extracting it.