Query Expressions for JSON in Python¶
JSONPath is a query language for selecting values from JSON-like data. A JSONPath query has the potential to return multiple values from a data structure, along with their locations.
This implementation is non-evaluating and read-only. We follow RFC 9535 and test against the JSONPath Compliance Test Suite.
Note
We use the term “JSON-like data” to describe arbitrary Python lists,
dictionaries, strings, numbers, Booleans and None, as you would get from
json.load(). When traversing dictionaries we ignore non-string keys.
See python-jsonpath if you need to query any Sequence
or Mapping instead of just lists and dictionaries.
Install¶
Install jsonpath-rfc9535 from PyPI using your favorite package manager.
pip
python -m pip install jsonpath-rfc9535
uv
uv add jsonpath-rfc9535
pipenv
pipenv install -u jsonpath-rfc9535
Examples¶
import jsonpath_rfc9535 as jsonpath
expr = "$.users[?@.status == 'pending'].name"
data: dict[str, object] = {
"users": [
{"id": "usr_101", "name": "Alice", "status": "pending"},
{"id": "usr_102", "name": "Bob", "status": "active"},
{"id": "usr_103", "name": "Charlie", "status": "pending"},
],
}
nodes = jsonpath.find(expr, data)
print(nodes.values()) # ['Alice', 'Charlie']
print(nodes.locations()) # [('users', 0, 'name'), ('users', 2, 'name')]
print(nodes.paths()) # ["$['users'][0]['name']", "$['users'][2]['name']"]
Or read data from a file:
import json
import jsonpath_rfc9535 as jsonpath
with open("path/to/some.json", encoding="utf-8") as fd:
data = json.load(fd)
nodes = jsonpath.find("$.some.query", data)
values = nodes.values()
# ...
You can query data from a YAML formatted file too, or any format that can be loaded into dictionaries and lists. If you have PyYAML installed:
import jsonpath_rfc9535 as jsonpath
import yaml
with open("some.yaml") as fd:
data = yaml.safe_load(fd)
values = jsonpath.find("$..products.*", data).values()
# ...