Extract elements from JSON using JSON path.
JSONPath is a query language for JSON data, similar to how XPath is used for XML. It allows you to extract specific data from a JSON structure using a concise and flexible syntax.
Here are some essential JSONPath operators:
Operator | Description |
---|---|
$ | Root element of the JSON |
. | Direct child (dot notation) |
[i] | Array indexing |
.. | Recursive descent (searches all levels) |
* | Wildcard (matches any property or array element) |
?() | Filter expression |
Consider the following JSON array:
$
)Returns the entire JSON array.
$.cities[0].name
)Returns the name of the first city in the array.
$..name
)Returns all the names in the JSON.
Differece between $..name and $[*].name
is that $..name
will return all the names in the JSON, including nested objects, while $[*].name
will only return the names of the objects in the root array.
For instance, using $[*].name
on the example JSON will return below:
$.cities[?(@.population > 3000000)]
)returns the cities with a population greater than 3,000,000.