JSONPath Next-Generation for Python
bc-jsonpath-ng is a robust and extended implementation of JSONPath for Python, aiming for standard compliance. It includes arithmetic and binary comparison operators and provides a clear Abstract Syntax Tree (AST) for metaprogramming, merging functionalities from `jsonpath-rw` and `jsonpath-rw-ext`. The current version is 1.6.1, and it receives active maintenance and updates.
Warnings
- gotcha The PyPI package name is `bc-jsonpath-ng`, but the primary import is `jsonpath_ng`. This can be a common point of confusion for new users.
- gotcha This library uses `` `this` `` (backtick-enclosed 'this') to reference the current object in JSONPath expressions, which differs from some other JSONPath implementations that use `@`.
- breaking Users of older Python versions should be aware that the `h2non/jsonpath-ng` fork (a related project, currently at v1.8.0) has dropped support for Python 3.8 and 3.9. While `bc-jsonpath-ng` v1.6.1 officially supports `>=3.8`, future updates or migrating to the `h2non` fork may require Python 3.10+.
- breaking In related `jsonpath-ng` versions (e.g., v1.8.0 from the `h2non` fork), string serialization of fields and child precedence has been made more conservative (e.g., enclosing fields in quotation marks, preserving precedence with parentheses). This could impact round-trip parsing consistency if exact string representations were relied upon.
Install
-
pip install bc-jsonpath-ng
Imports
- jsonpath, parse
from jsonpath_ng import jsonpath, parse
- JSONPath programmatic components
from jsonpath_ng.jsonpath import Fields, Root, Slice, Child, Where
Quickstart
import json
from jsonpath_ng import jsonpath, parse
data = {
"store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "E.B. White",
"title": "Charlotte's Web",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
# Example 1: Find all book titles
jsonpath_expr_titles = parse('$.store.book[*].title')
titles = [match.value for match in jsonpath_expr_titles.find(data)]
print(f"Book Titles: {titles}")
# Example 2: Find prices of books cheaper than 10
jsonpath_expr_cheap_books = parse('$.store.book[?price < 10].price')
cheap_prices = [match.value for match in jsonpath_expr_cheap_books.find(data)]
print(f"Prices of cheap books: {cheap_prices}")
# Example 3: Accessing full path of matches
jsonpath_expr_all_prices = parse('$.store..price')
for match in jsonpath_expr_all_prices.find(data):
print(f"Full path: {match.full_path}, Value: {match.value}")