JSONPath for Python
The `jsonpath` library provides a Pythonic implementation of JSONPath, following the IETF JSONPath draft specification. It allows users to query JSON-like data structures using XPath-like expressions. It's actively developed, with the latest version being 0.82.2, and typically releases updates as the IETF draft progresses or new features are added.
Warnings
- breaking This library strictly adheres to the IETF JSONPath draft. Its syntax and behavior may differ significantly from other popular Python JSONPath implementations (e.g., `jsonpath_rw`, `jsonpath-ng`). Users migrating or expecting behavior from non-standard JSONPath libraries should carefully review the IETF specification and library documentation.
- gotcha For repeated queries with the same JSONPath expression, using `jsonpath.select()` repeatedly is less efficient than instantiating a `JSONPath` object once and calling its `findall()` method. `select()` re-compiles the path on each call.
- gotcha The `JSONPath` object has both `find()` and `findall()` methods. `find()` returns the first matching element (or `None`), while `findall()` returns a list of all matching elements. Confusing these can lead to unexpected results (e.g., only getting one match when multiple exist).
Install
-
pip install jsonpath
Imports
- jsonpath
import jsonpath
- JSONPath
from jsonpath import JSONPath
- select
from jsonpath import select
Quickstart
import jsonpath
data = {
"store": {
"book": [
{"category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95},
{"category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99}
],
"bicycle": {"color": "red", "price": 19.95}
}
}
# Use the convenience 'select' function to query data
path_expression = "$.store.book[*].author"
authors = jsonpath.select(path_expression, data)
print(f"Authors found: {authors}")
# For performance-critical scenarios, compile the path once using JSONPath class
from jsonpath import JSONPath
json_path = JSONPath(path_expression)
authors_compiled = json_path.findall(data)
print(f"Authors (compiled path): {authors_compiled}")