JSONPath, JSON Pointer and JSON Patch for Python
Python JSONPath is a flexible engine for processing JSONPath, JSON Pointer, and JSON Patch expressions. It aims to be compliant with RFC 9535 for JSONPath, RFC 6901 for JSON Pointer, and RFC 6902 for JSON Patch. The library is currently at version 2.0.2 and receives regular updates and maintenance, often with a few releases per year.
Warnings
- breaking Version 2.0.0 introduced significant breaking changes to JSONPath syntax in the default configuration. Unquoted property names are no longer treated as literals in bracket notation. It also introduced a new 'strict mode' enforcing full RFC 9535 compliance.
- breaking JSON Pointers with negative indices are no longer permitted by default, aligning with RFC 6901. Attempting to use a negative index will raise a `JSONPointerIndexError`.
- breaking Support for Python 3.7 was dropped.
- gotcha Parsing of non-standard JSONPath regular expression literals containing an escaped solidus (`/`) was incorrect prior to v2.0.2, affecting queries using the regex operator `=~`.
- gotcha The non-standard JSON Patch operation `addap` (add-after-property) was behaving incorrectly, like `addne` (add-if-not-exists), in versions prior to 1.3.1. Also, JSON Patch operations on mappings with integer-like targets could behave unexpectedly.
Install
-
pip install python-jsonpath
Imports
- jsonpath
import jsonpath
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},
{"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 the titles of all books
book_titles = jsonpath.findall("$.store.book[*].title", data)
print(f"Book Titles: {book_titles}")
# Find all books cheaper than $10
cheap_books = jsonpath.findall("$.store.book[?(@.price < 10)].title", data)
print(f"Cheap Book Titles: {cheap_books}")
# Compile a JSONPath expression for repeated use
compiled_path = jsonpath.compile("$.store.book[?(@.category == 'fiction')].author")
fiction_authors = compiled_path.findall(data)
print(f"Fiction Authors: {fiction_authors}")