JSONPath-NG

1.8.0 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

This quickstart demonstrates how to parse JSON data, extract specific elements using JSONPath expressions, filter results, and update values within a JSON structure. It covers the core `parse` and `find` methods, as well as a basic `update` operation.

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']}")

view raw JSON →