JSONPath-NG
jsonpath-ng is a robust and significantly extended implementation of JSONPath for Python. It aims to be standard compliant, including arithmetic and binary comparison operators, and provides a clear Abstract Syntax Tree (AST) for metaprogramming. As of version 1.8.0, it is actively maintained with a regular release cadence, merging functionalities from older libraries like jsonpath-rw and jsonpath-rw-ext.
Warnings
- breaking Python 3.7 support was removed in v1.7.0. Python 3.8 and 3.9 support were removed in v1.8.0. Users on these Python versions must upgrade to Python 3.10 or newer to use jsonpath-ng >= 1.8.0.
- gotcha The `find()` method returns a list of `DatumInContext` objects, even if only one or no matches are found. Users commonly forget to check if the list is empty before accessing `[0].value`, leading to an `IndexError`.
- gotcha In older versions, updating a JSON object using `jsonpath_expr.update()` could fail with `TypeError` if the target value was `None` or a boolean. While fixes have been implemented (e.g., for boolean values in v1.7.0, and null values in earlier patches), ensure you are on a recent version if experiencing such issues.
- gotcha The library internally uses `this` to refer to the 'current object' within a filter expression, rather than the `@` symbol often seen in other JSONPath implementations. While `@` might work in simple cases due to parsing ambiguities, `this` is the explicit and recommended syntax for clarity and correctness.
Install
-
pip install jsonpath-ng
Imports
- parse
from jsonpath_ng import parse
- jsonpath
from jsonpath_ng import jsonpath
Quickstart
from jsonpath_ng import jsonpath, parse
import json
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},
{"category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99},
{"category": "fiction", "author": "J.R.R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99}
],
"bicycle": {"color": "red", "price": 19.95}
},
"expensive": 10
}
# Find all book titles
jsonpath_expr = parse('$.store.book[*].title')
matches = jsonpath_expr.find(data)
book_titles = [match.value for match in matches]
print(f"Book Titles: {book_titles}")
# Find books cheaper than $10
jsonpath_expr = parse('$.store.book[?(@.price < 10)].title')
matches = jsonpath_expr.find(data)
cheap_books = [match.value for match in matches]
print(f"Cheap Books (titles): {cheap_books}")
# Update a value (e.g., change bicycle color)
update_expr = parse('$.store.bicycle.color')
updated_data = update_expr.update(data, 'blue')
print(f"Updated Bicycle Color: {updated_data['store']['bicycle']['color']}")