Python JSONPath
JSONPath is a mini language for selecting values from data formatted in JavaScript Object Notation, or equivalent Python objects, like dictionaries and lists.
Python JSONPath is a non-evaluating, read-only implementation of JSONPath, suitable for situations where JSONPath query authors are untrusted. We follow RFC 9535 and test against the JSONPath Compliance Test Suite.
We also include implementations of JSON Pointer (RFC 6901) and JSON Patch (RFC 6902), plus methods for converting a JSONPathMatch to a JSONPointer
.
Install
Install Python JSONPath using pip:
Or Pipenv:
Or pipx
Or from conda-forge:
Optional dependencies
Python JSONPath works out of the box with no extra dependencies, and its syntax is already very close to RFC 9535.
For strict compliance with the specification, strict mode and the strict
extra were added in version 2.0.0.
This installs regex
and iregexp-check
, enabling:
match()
andsearch()
to useregex
instead of Python's built-inre
module.- Validation of regular expressions against RFC 9485.
See the syntax guide for strict mode details and specification extensions.
Example
import jsonpath
example_data = {
"categories": [
{
"name": "footwear",
"products": [
{
"title": "Trainers",
"description": "Fashionable trainers.",
"price": 89.99,
},
{
"title": "Barefoot Trainers",
"description": "Running trainers.",
"price": 130.00,
},
],
},
{
"name": "headwear",
"products": [
{
"title": "Cap",
"description": "Baseball cap",
"price": 15.00,
},
{
"title": "Beanie",
"description": "Winter running hat.",
"price": 9.00,
},
],
},
],
"price_cap": 10,
}
products = jsonpath.findall("$..products.*", example_data)
print(products)
Which results in a list of all products from all categories:
[
{
"title": "Trainers",
"description": "Fashionable trainers.",
"price": 89.99
},
{
"title": "Barefoot Trainers",
"description": "Running trainers.",
"price": 130.0
},
{
"title": "Cap",
"description": "Baseball cap",
"price": 15.0
},
{
"title": "Beanie",
"description": "Winter running hat.",
"price": 9.0
}
]
Or, reading data from a JSON formatted file:
import jsonpath
with open("some.json") as fd:
products = jsonpath.findall("$..products.*", fd)
print(products)
You could use Python JSONPath on data read from a YAML formatted file too, or any data format that can be loaded into dictionaries and lists. If you have PyYAML installed:
import jsonpath
import yaml
with open("some.yaml") as fd:
data = yaml.safe_load(fd)
products = jsonpath.findall("$..products.*", data)
print(products)
Next Steps
Have a read through the Quick Start and High Level API Reference, or the default JSONPath Syntax supported by Python JSONPath.
If you're interested in customizing JSONPath, take a look at Advanced Usage and the Low Level API Reference.