A robust and significantly extended implementation of JSONPath for Python, with a clear AST for metaprogramming.
—
Command-line tool for querying JSON files using JSONPath expressions. The tool supports both file input and stdin processing, with glob pattern matching for multiple files and formatted output of matching values.
Entry point for the command-line interface with argument parsing and file processing.
def main(*argv):
"""
Main CLI function for jsonpath.py command-line tool.
Parses command line arguments and processes JSON files with JSONPath queries.
Parameters:
- argv: tuple, command line arguments [program_name, expression, files...]
If no files provided, reads from stdin
Usage:
jsonpath.py <expression> [files...]
Examples:
jsonpath.py '$.users[*].name' data.json
jsonpath.py '$.*.price' *.json
cat data.json | jsonpath.py '$.items[0]'
"""
def entry_point():
"""
Console script entry point installed as 'jsonpath.py' command.
Calls main() with sys.argv arguments.
"""Functions for processing individual JSON files and handling match output.
def find_matches_for_file(expr, f):
"""
Find JSONPath matches in a JSON file.
Parameters:
- expr: JSONPath object, compiled JSONPath expression
- f: file-like object, JSON file to search
Returns:
list[DatumInContext]: Matching values with context
Raises:
json.JSONDecodeError: If file contains invalid JSON
"""
def print_matches(matches):
"""
Print match values to stdout.
Parameters:
- matches: list[DatumInContext], matches to print
Output:
Prints each match value on a separate line using str() formatting
"""The command-line tool is installed automatically with the package:
pip install jsonpath-rwThis creates a jsonpath.py console command.
jsonpath.py <expression> [files...]<expression>: JSONPath expression string (required)[files...]: JSON files to search (optional, uses stdin if not provided)# Find all user names
jsonpath.py '$.users[*].name' data.json
# Get first item's price
jsonpath.py '$.items[0].price' inventory.json
# Find all nested values
jsonpath.py '$..*' config.json# Search all JSON files in directory
jsonpath.py '$.version' *.json
# Search specific pattern
jsonpath.py '$.errors[*]' logs/*.json
# Multiple explicit files
jsonpath.py '$.status' file1.json file2.json file3.json# Pipe JSON data
cat data.json | jsonpath.py '$.results[*].id'
# From curl
curl -s https://api.example.com/data | jsonpath.py '$.items[*].name'
# From other commands
echo '{"test": [1,2,3]}' | jsonpath.py '$.test[*]'# Filtering with where clause
jsonpath.py '$.users[*] where @.active' users.json
# Union of multiple paths
jsonpath.py '$.name|$.title' metadata.json
# Descendant search
jsonpath.py '$..price' catalog.json
# Field selection
jsonpath.py '$.user["first_name","last_name"]' profile.json# Invalid JSONPath expression
jsonpath.py '$.invalid[syntax' data.json
# Output: Parse error at 1:15 near token syntax (ID)
# Invalid JSON file
jsonpath.py '$.test' invalid.json
# Output: JSON decode error
# File not found
jsonpath.py '$.test' missing.json
# Output: File system errorThe command-line tool includes comprehensive help information:
jsonpath.py --helpOutput:
usage: jsonpath.py [-h] expression [file ...]
Search JSON files (or stdin) according to a JSONPath expression.
positional arguments:
expression A JSONPath expression.
file Files to search (if none, searches stdin)
optional arguments:
-h, --help show this help message and exit
Quick JSONPath reference (see more at https://github.com/kennknowles/python-jsonpath-rw)
atomics:
$ - root object
`this` - current object
operators:
path1.path2 - same as xpath /
path1|path2 - union
path1..path2 - somewhere in between
fields:
fieldname - field with name
* - any field
[_start_?:_end_?] - array slice
[*] - any array indexThe tool outputs matching values one per line using Python's default string representation:
# Simple values
jsonpath.py '$.count' data.json
# Output: 42
# String values
jsonpath.py '$.name' data.json
# Output: Alice
# Complex objects
jsonpath.py '$.user' data.json
# Output: {'name': 'Alice', 'age': 30}
# Arrays
jsonpath.py '$.items' data.json
# Output: [1, 2, 3]
# Multiple matches
jsonpath.py '$.users[*].name' data.json
# Output:
# Alice
# Bob
# Charlie#!/bin/bash
# Extract version from package.json files
for file in */package.json; do
version=$(jsonpath.py '$.version' "$file")
echo "$(dirname "$file"): $version"
done# Complex data processing pipeline
curl -s https://api.example.com/users | \
jsonpath.py '$.data[*]' | \
while IFS= read -r user; do
echo "$user" | jsonpath.py '$.name'
done# Validate expected structure exists
if jsonpath.py '$.config.database.host' config.json > /dev/null; then
echo "Configuration valid"
else
echo "Missing database host configuration"
exit 1
fiInstall with Tessl CLI
npx tessl i tessl/pypi-jsonpath-rw