JSONPath-RW
JSONPath-RW (jsonpath-rw) is a Python library that provides a robust and extended implementation of JSONPath, featuring a clear Abstract Syntax Tree (AST) for metaprogramming. As of its last release (1.4.0 in April 2015), it was primarily tested with Python 2.7, 3.4, 3.5, 3.6, and 3.7. While functional, its development is inactive, and more actively maintained and feature-rich alternatives like `jsonpath-ng` are now available, which merge its capabilities with `jsonpath-rw-ext` for modern Python versions.
Warnings
- deprecated The `jsonpath-rw` library is no longer actively maintained. For modern Python applications (3.8+), consider using `jsonpath-ng` (jsonpath-ng.readthedocs.io), which merges the features of `jsonpath-rw` and `jsonpath-rw-ext` and offers active development and broader Python version support.
- gotcha Filtering expressions (e.g., `[?()]`) are not directly supported by `jsonpath-rw`'s default parser. Attempting to use them will result in a `ParseError`. These extensions are available through the companion library `jsonpath-rw-ext`.
- gotcha The underlying parsing toolkit, PLY, does not work when Python docstrings are removed (e.g., by running Python with `PYTHONOPTIMIZE=2` or `python -OO`). This can lead to unexpected failures.
- gotcha The `jsonpath-rw` library, as of version 1.4.0, was primarily tested with Python versions up to 3.7. While it might function on newer Python versions, active development and testing for compatibility beyond 3.7 is not ongoing. There have been reports of build failures with newer `setuptools` versions.
Install
-
pip install jsonpath-rw
Imports
- parse
from jsonpath_rw import parse
- jsonpath
from jsonpath_rw import jsonpath
Quickstart
from jsonpath_rw import jsonpath, parse
# Example JSON data
data = {'foo': [{'baz': 1}, {'baz': 2}, {'qux': 3}]}
# Parse a JSONPath expression
jsonpath_expr = parse('foo[*].baz')
# Find matches in the data
matches = [match.value for match in jsonpath_expr.find(data)]
print(f"Extracted values: {matches}")
# Access full path of matches
full_paths = [str(match.full_path) for match in jsonpath_expr.find(data)]
print(f"Full paths of matches: {full_paths}")
# Programmatic expression building
from jsonpath_rw.jsonpath import Fields, Slice, Child
jsonpath_expr_direct = Fields('foo').child(Slice('*')).child(Fields('baz'))
matches_direct = [match.value for match in jsonpath_expr_direct.find(data)]
print(f"Extracted values (programmatic): {matches_direct}")