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 most of RFC 9535. See Notable differences for a list of areas where we deviate from the standard.
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:
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.