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 Python JSONPath using pip:
pip install python-jsonpathOr Pipenv:
pipenv install python-jsonpathOr pipx
pipx install python-jsonpathOr from conda-forge:
conda install -c conda-forge python-jsonpathBy default, and without any additional dependencies, the syntax supported by Python JSONPath is very close to RFC 9535. For strict compatibility with the specification, install regex and iregexp-check packages too.
With these two packages installed, the match() and search() filter functions will use regex instead of re from the standard library, and will validate regular expression patterns against RFC 9485.
See the syntax guide for more information about strict compatibility with RFC 9535 and extensions to the specification.
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)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.