JSONPath does for JSON processing what XPath (defined as a W3C standard) does for XML. JSONPath queries can be super useful, and are a great addition to any developer or ops person’s toolbox.
You may want to do a quick data query, test, or run through some JSON parsing scenarios for your code. If you have your data easily available in JSON format, then using JSONPath queries or expressions can be a great way to filter your data quickly and efficiently.
JSONPath 101
JSONPath expressions use $
to refer to the outer level object. If for example you have an array at the root, $
would refer to that array.
When writing JSONPath expressions, you can use dot notation or bracket notation. For example:
$.animals.land[0].weight
$['animals']['land'][0]['weight']
You can use filter expressions to filter out specific items in your queries. For example: ?(<bool expression>)
Here is an example that would filter our collection of land animals to show only those heavier than 50.0, returning their names:
$.animals.land[?(@.weight > 50.0)].name
The wildcard character *
is used to select all objects or elements.
Note the @
symbol that is used to select the ‘current’ item being iterated in the boolean expression.
There are more JSONPath syntax elements to learn about, but the above are what I find most useful and commonly required.
JSONPath Query Example
Here is a chunk of JSON data, and some basic queries that show how you can easily filter down the dataset and select what you need.
JSONPath Queries – Example 1
Find all “Report runs” where root.id
is equal to a specific value:
$.runs[?(@.root.id=="af1bcd6b-406f-43f9-86b3-9f01ee211ddc")]
JSONPath Queries – Example 2 (AND operator)
Find all “Report runs” where root.id
is equal to a specific value, and shell.id
is equal to a specific value:
$..runs[?(@.root.id=="af1bcd6b-406f-43f9-86b3-9f01ee211ddc" && @.shell.id=='d743537e393d')]
Useful JSONPath Resources
Use this webapp to write and test JSONPath expressions live in your browser.
- Work with JSONPath in your Javascript / nodejs apps: JSONPath-Plus npm.
- Use JSONPath in your Java projects: com.jayway.jsonpath Maven
- JSONPath for .NET: JsonPath.Net nuget package.