### Install Python JSONPath Source: https://github.com/jg-rp/python-jsonpath/blob/main/README.md Instructions for installing the python-jsonpath library using package managers like pip, pipenv, and conda-forge. ```bash pip install python-jsonpath ``` ```bash pipenv install -u python-jsonpath ``` ```bash conda install -c conda-forge python-jsonpath ``` -------------------------------- ### JSONPath Environment Shortcut Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/quickstart.md Demonstrates the shortcut usage of findall(), finditer(), and compile() which utilize the default JSONPathEnvironment. It shows the equivalent explicit instantiation and usage. ```python jsonpath.findall(path, data) # Equivalent to: jsonpath.JSONPathEnvironment().compile(path).findall(data) ``` -------------------------------- ### JSONPath Environment API Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/quickstart.md Documentation for the JSONPathEnvironment class, which serves as the default environment for JSONPath operations. It outlines the methods available for compiling paths and finding data. ```APIDOC JSONPathEnvironment: compile(path: str) -> CompiledJSONPath Compiles a JSONPath expression into a reusable object. Parameters: path: The JSONPath expression string. Returns: A CompiledJSONPath object. findall(path: str, data: dict | list) -> list Finds all matching values in the data for the given path. Parameters: path: The JSONPath expression string. data: The JSON data (dictionary or list) to query. Returns: A list of matching values. finditer(path: str, data: dict | list) -> Iterator[Match] Returns an iterator yielding matches for the given path. Parameters: path: The JSONPath expression string. data: The JSON data (dictionary or list) to query. Returns: An iterator of Match objects. ``` -------------------------------- ### JSONPath Query Example Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Finds objects in `source.json` that match the provided JSONPath query and writes the results to `result.json`. ```console $ json path -q "$.foo['bar'][?@.baz > 1]" -f source.json -o result.json ``` -------------------------------- ### JSON Pointer Command Usage Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Provides an example of using the `json pointer` command to resolve a JSON Pointer against a JSON document. ```console $ json pointer -p "/categories/0/name" -f /tmp/source.json ``` -------------------------------- ### Find First Match with JSONPath Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/quickstart.md Demonstrates the `jsonpath.match()` function, introduced in version 0.8.0, which returns a `JSONPathMatch` object for the first match found in the data, or `None` if no matches are found. It accepts the same arguments as `findall()`. ```python import jsonpath data = { "users": [ { "name": "Sue", "score": 100, }, { "name": "John", "score": 86, }, { "name": "Sally", "score": 84, }, { "name": "Jane", "score": 55, }, ] } match = jsonpath.match("$.users[?@.score > 85].name", data) if match: print(match.obj) ``` -------------------------------- ### Install Python JSONPath with pip Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/index.md Install the Python JSONPath library using pip, pipenv, pipx, or conda. This allows you to use JSONPath expressions to query JSON data. ```console pip install python-jsonpath ``` ```console pipenv install python-jsonpath ``` ```console pipx install python-jsonpath ``` ```console conda install -c conda-forge python-jsonpath ``` -------------------------------- ### Find products in JSON file using JSONPath Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/index.md Use jsonpath.findall to extract data from a JSON file. This example demonstrates how to open a JSON file and find all products within the JSON structure. ```python import jsonpath with open("some.json") as fd: products = jsonpath.findall("$..products.*", fd) print(products) ``` -------------------------------- ### JSONPath Example Source: https://github.com/jg-rp/python-jsonpath/blob/main/README.md Demonstrates how to use the python-jsonpath library to query JSON data using JSONPath expressions. It shows finding user names based on a score condition. ```python import jsonpath data = { "users": [ {"name": "Sue", "score": 100}, {"name": "John", "score": 86}, {"name": "Sally", "score": 84}, {"name": "Jane", "score": 55}, ] } user_names = jsonpath.findall("$.users[?@.score < 100].name", data) print(user_names) # ['John', 'Sally', 'Jane'] ``` -------------------------------- ### Iterate Over Matches with JSONPath Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/quickstart.md Explains how to use `jsonpath.finditer()` to iterate over `JSONPathMatch` objects for each match found in the data. This method accepts the same arguments as `findall()` and provides access to the matched object (`obj`) and its path (`path`). ```python import jsonpath data = { "users": [ { "name": "Sue", "score": 100, }, { "name": "John", "score": 86, }, { "name": "Sally", "score": 84, }, { "name": "Jane", "score": 55, }, ] } matches = jsonpath.finditer("$.users.*.name", data) for match in matches: print(match) ``` -------------------------------- ### JSON Pointer Resolution Example Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Resolves a JSON Pointer against `source.json` and pretty-prints the result to standard output. ```console $ json --pretty pointer -p "/foo/bar/0" -f source.json ``` -------------------------------- ### JSON Patch Application Example Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Applies a JSON Patch defined in `patch.json` to JSON data read from standard input and writes the patched JSON to `result.json`. ```console $ cat source.json | json patch /path/to/patch.json -o result.json ``` -------------------------------- ### Compile JSONPath for Reuse Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/quickstart.md Shows how to use `jsonpath.compile()` to create a reusable `JSONPath` object from a path string. Compiled paths can then be used with their own `findall()` and `finditer()` methods, improving performance when querying multiple data sources with the same path. ```python import jsonpath some_data = { "users": [ { "name": "Sue", "score": 100, }, { "name": "John", "score": 86, }, ] } other_data = { "users": [ { "name": "Sally", "score": 84, }, { "name": "Jane", "score": 55, }, ] } path = jsonpath.compile("$.users.*.name") some_users = path.findall(some_data) other_users = path.findall(other_data) print(some_users) print(other_users) ``` -------------------------------- ### Find All Matches with JSONPath Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/quickstart.md Demonstrates how to use `jsonpath.findall()` to retrieve all values that match a given JSONPath expression. It can query Python dictionaries, lists, JSON strings, or file-like objects. The function always returns a list of results. ```python import jsonpath data = { "users": [ { "name": "Sue", "score": 100, }, { "name": "John", "score": 86, }, { "name": "Sally", "score": 84, }, { "name": "Jane", "score": 55, }, ] } user_names = jsonpath.findall("$.users.*.name", data) print(user_names) ``` ```python import jsonpath with open("users.json") as fd: user_names = jsonpath.findall("$.users.*.name", fd) print(user_names) ``` -------------------------------- ### Check Python JSONPath Version Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Displays the installed version of the Python JSONPath library. This is a global option available for all commands. ```console $ json --version python-jsonpath, version 0.9.0 ``` -------------------------------- ### JSONPath Filter Expression Example Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/advanced.md An example of a JSONPath filter expression that uses a custom `min` function to select elements where the price is equal to the minimum price among all products. ```jsonpath $..products[?@.price == min($..products.price)] ``` -------------------------------- ### JSON Pointer Example Source: https://github.com/jg-rp/python-jsonpath/blob/main/README.md Illustrates the usage of the RFC 6901 compliant JSON Pointer implementation within the python-jsonpath library. It shows how to resolve values in JSON data using pointer strings or lists. ```python from jsonpath import pointer data = { "users": [ {"name": "Sue", "score": 100}, {"name": "John", "score": 86}, {"name": "Sally", "score": 84}, {"name": "Jane", "score": 55}, ] } sue_score = pointer.resolve("/users/0/score", data) print(sue_score) # 100 jane_score = pointer.resolve(["users", 3, "score"], data) print(jane_score) # 55 ``` -------------------------------- ### Find products in YAML file using JSONPath Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/index.md Use jsonpath.findall to extract data from a YAML file. This example demonstrates how to load YAML data into a Python dictionary and find all products within the structure. Requires PyYAML. ```python import jsonpath import yaml with open("some.yaml") as fd: data = yaml.safe_load(fd) products = jsonpath.findall("$..products.*", data) print(products) ``` -------------------------------- ### Subclass JSONPathEnvironment to Customize Functions Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/advanced.md Shows how to subclass JSONPathEnvironment and override `setup_function_extensions` to add custom functions or modify existing ones. Includes an example of adding a 'min' filter. ```python from typing import Iterable import jsonpath class MyEnv(jsonpath.JSONPathEnvironment): def setup_function_extensions(self) -> None: super().setup_function_extensions() self.function_extensions["properties"] = self.function_extensions["keys"] self.function_extensions["min"] = min_filter def min_filter(obj: object) -> object: if not isinstance(obj, Iterable): return jsonpath.UNDEFINED try: return min(obj) except TypeError: return jsonpath.UNDEFINED env = MyEnv() ``` -------------------------------- ### Find products in JSON data using JSONPath Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/index.md Use jsonpath.findall to extract data from a Python dictionary representing JSON data. This example demonstrates how to find all products within a nested JSON structure. ```python import jsonpath example_data = { "categories": [ { "name": "footwear", "products": [ { "title": "Trainers", "description": "Fashionable trainers.", "price": 89.99, }, { "title": "Barefoot Trainers", "description": "Running trainers.", "price": 130.00, }, ], }, { "name": "headwear", "products": [ { "title": "Cap", "description": "Baseball cap", "price": 15.00, }, { "title": "Beanie", "description": "Winter running hat.", "price": 9.00, }, ], }, ], "price_cap": 10, } products = jsonpath.findall("$..products.*", example_data) print(products) ``` ```json [ { "title": "Trainers", "description": "Fashionable trainers.", "price": 89.99 }, { "title": "Barefoot Trainers", "description": "Running trainers.", "price": 130.0 }, { "title": "Cap", "description": "Baseball cap", "price": 15.0 }, { "title": "Beanie", "description": "Winter running hat.", "price": 9.0 } ] ``` -------------------------------- ### Filter Expression Examples Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/syntax.md Demonstrates various filter expressions using comparison, logical, and regex operators. Filters allow nodes to be removed from a selection based on a boolean expression. ```text $..products[?(@.price < $.price_cap)] ``` ```text $..products[?@.price < $.price_cap] ``` ```text $..products[?(@.description =~ /.*trainers/i)] ``` ```text $..products[?!@.sale_price] ``` ```text $..products[?@.sale_price == undefined] ``` ```text $.categories[?count(@.products.*) >= 2] ``` -------------------------------- ### Slice Selectors ([0:-1], [-1:0:-1]) Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/syntax.md Select a range of elements from an array using slice notation. Start index, stop index, and step are optional. ```text $.categories[0:] ``` ```text $.categories[0:-1:] ``` ```text $.categories[0:-1:1] ``` ```text $.categories[::] ``` -------------------------------- ### Apply JSON Patch Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/quickstart.md Applies a JSON Patch document to a target JSON data structure. The patch can be provided as a string, file-like object, or an iterable of operations. The data is modified in place if it's a Python structure, or loaded if it's a string/file. ```python from jsonpath import patch patch_operations = [ {"op": "add", "path": "/some/foo", "value": {"foo": {}}}, {"op": "add", "path": "/some/foo", "value": {"bar": []}}, {"op": "copy", "from": "/some/other", "path": "/some/foo/else"}, {"op": "add", "path": "/some/foo/bar/-", "value": 1}, ] data = {"some": {"other": "thing"}} patch.apply(patch_operations, data) print(data) # {'some': {'other': 'thing', 'foo': {'bar': [1], 'else': 'thing'}}} ``` ```python from jsonpath import JSONPatch patch = JSONPatch( [ {"op": "add", "path": "/some/foo", "value": {"foo": {}}}, {"op": "add", "path": "/some/foo", "value": {"bar": []}}, {"op": "copy", "from": "/some/other", "path": "/some/foo/else"}, {"op": "add", "path": "/some/foo/bar/-", "value": 1}, ] ) data = {"some": {"other": "thing"}} patch.apply(data) print(data) # {'some': {'other': 'thing', 'foo': {'bar': [1], 'else': 'thing'}}} ``` ```python from jsonpath import JSONPatch patch = ( JSONPatch() .add("/some/foo", {"foo": []}) .add("/some/foo", {"bar": []}) .copy("/some/other", "/some/foo/else") .add("/some/foo/bar/-", "/some/foo/else") ) data = {"some": {"other": "thing"}} patch.apply(data) print(data) # {'some': {'other': 'thing', 'foo': {'bar': [1], 'else': 'thing'}}} ``` -------------------------------- ### Resolve JSON Pointer Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/quickstart.md Resolves a JSON Pointer against a JSON document. Supports string or list representations of pointers and various data inputs (Python structures, JSON strings, file-like objects). Raises JSONPointerResolutionError subclasses on failure, or returns a default value if provided. ```python from jsonpath import pointer data = { "users": [ { "name": "Sue", "score": 100, }, { "name": "John", "score": 86, }, { "name": "Sally", "score": 84, }, { "name": "Jane", "score": 55, }, ] } sue_score = pointer.resolve("/users/0/score", data) print(sue_score) # 100 jane_score = pointer.resolve(["users", 3, "score"], data) print(jane_score) # 55 ``` ```python from jsonpath import pointer data = { "users": [ { "name": "Sue", "score": 100, }, { "name": "John", "score": 86, }, ] } sue_score = pointer.resolve("/users/99/score", data, default=0) print(sue_score) # 0 ``` -------------------------------- ### Customizing Identifier Tokens in JSONPathEnvironment Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/advanced.md Demonstrates how to change default identifier tokens, such as the root token, by subclassing `JSONPathEnvironment` and setting attributes like `root_token`. Includes an example of using a custom root token. ```python import JSONPathEnvironment class MyJSONPathEnvironment(JSONPathEnvironment): root_token = "^" data = { "users": [ {"name": "Sue", "score": 100}, {"name": "John", "score": 86}, {"name": "Sally", "score": 84}, {"name": "Jane", "score": 55}, ], "limit": 100, } env = MyJSONPathEnvironment() user_names = env.findall( "^.users[?@.score < ^.limit].name", data, ) ``` -------------------------------- ### Custom Filter Function Extension Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/advanced.md Shows how to extend Python JSONPath with custom filter functions by creating a class that inherits from `jsonpath.function_extensions.FilterFunction`. This example implements a `min()` function to find the minimum value in a sequence. ```python from typing import Iterable import jsonpath from jsonpath.function_extensions import ExpressionType from jsonpath.function_extensions import FilterFunction class MinFilterFunction(FilterFunction): """A JSONPath function extension returning the minimum of a sequence.""" arg_types = [ExpressionType.VALUE] return_type = ExpressionType.VALUE def __call__(self, value: object) -> object: if not isinstance(value, Iterable): return jsonpath.UNDEFINED try: return min(value) except TypeError: return jsonpath.UNDEFINED env = jsonpath.JSONPathEnvironment() env.function_extensions["min"] = MinFilterFunction() example_data = {"foo": [{"bar": [4, 5]}, {"bar": [1, 5]}]} print(env.findall("$.foo[?min(@.bar) > 1]", example_data)) ``` -------------------------------- ### Display Help Information Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Shows the general help message for the `json` command, listing available commands and global options. Use `json COMMAND --help` for command-specific help. ```console $ json --help usage: json [-h] [--debug] [--pretty] [-v] [--no-unicode-escape] COMMAND ... JSONPath, JSON Pointer and JSON Patch utilities. positional arguments: COMMAND path Find objects in a JSON document given a JSONPath. pointer Resolve a JSON Pointer against a JSON document. patch Apply a JSON Patch to a JSON document. optional arguments: -h, --help show this help message and exit --debug Show stack traces. (default: False) --pretty Add indents and newlines to output JSON. (default: False) -v, --version Show the version and exit. --no-unicode-escape Disable decoding of UTF-16 escape sequence within paths and pointers. (default: False) Use [json COMMAND --help] for command specific help. ``` -------------------------------- ### JSONPath CLI Options Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Details the command-line options available for the `json path` command, including query, path file, input file, and output file. ```APIDOC json path [-h] (-q QUERY | -r PATH_FILE) [-f FILE] [-o OUTPUT] Arguments: -h, --help show this help message and exit -q QUERY, --query QUERY The JSONPath as a string. -r PATH_FILE, --path-file PATH_FILE The path to a file containing a JSONPath. -f FILE, --file FILE The path to a file containing the target JSON document. If omitted or a hyphen (-), the target JSON document will be read from the standard input stream. -o OUTPUT, --output OUTPUT The path to a file to write resulting objects to, as a JSON array. If omitted or a hyphen (-) is given, results will be written to the standard output stream. --no-unicode-escape Disable decoding of UTF-16 escape sequences, including surrogate paris. This can improve performance if you know your paths and pointers don't contain UTF-16 escape sequences. --no-type-checks Disables JSONPath filter expression well-typedness checks. The well-typedness of a filter expression is defined by RFC 9535. ``` -------------------------------- ### JSONPath Command Help Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Displays detailed help for the `json path` command, including its specific arguments for querying JSON documents. ```console $ json path --help usage: json path [-h] (-q QUERY | -r PATH_FILE) [-f FILE] [-o OUTPUT] Find objects in a JSON document given a JSONPath. optional arguments: -h, --help show this help message and exit -q QUERY, --query QUERY JSONPath query string. -r PATH_FILE, --path-file PATH_FILE Text file containing a JSONPath query. -f FILE, --file FILE File to read the target JSON document from. Defaults to reading from the standard input stream. -o OUTPUT, --output OUTPUT File to write resulting objects to, as a JSON array. Defaults to the standard output stream. --no-type-checks Disables filter expression well-typedness checks. ``` -------------------------------- ### JSON Pointer CLI Options Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Details the command-line options available for the `json pointer` command, including pointer, pointer file, input file, output file, and URI decoding. ```APIDOC json pointer [-h] (-p POINTER | -r POINTER_FILE) [-f FILE] [-o OUTPUT] [-u] Arguments: -h, --help show this help message and exit -p POINTER, --pointer POINTER An RFC 6901 formatted JSON Pointer string. -r POINTER_FILE, --pointer-file POINTER_FILE The path to a file containing a JSON Pointer. -f FILE, --file FILE The path to a file containing the target JSON document. If omitted or a hyphen (-), the target JSON document will be read from the standard input stream. -o OUTPUT, --output OUTPUT The path to a file to write the resulting object to. If omitted or a hyphen (-) is given, results will be written to the standard output stream. -u, --uri-decode Enable URI decoding of the JSON Pointer. In this example, we would look for a property called "hello world" in the root of the target document. ``` -------------------------------- ### JSON Patch Command with Standard Input Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Demonstrates applying a JSON Patch by piping the patch content from standard input. ```console $ cat /tmp/patch.json | json patch - -f /tmp/target.json ``` -------------------------------- ### JSON Pointer Command with Pointer File Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Demonstrates how to use the `json pointer` command when the JSON Pointer is provided in a file. ```console $ json pointer -r /tmp/pointer.txt -f /tmp/source.json ``` -------------------------------- ### Union and Intersection Operators Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/syntax.md Shows examples of the union (`|`) and intersection (`&`) operators for combining or finding common matches between multiple JSONPath expressions. These operators are not allowed within filter expressions. ```text $..products.*.price | $.price_cap ``` ```text $.categories[?(@.name == 'footwear')].products.* & $.categories[?(@.name == 'headwear')].products.* ``` -------------------------------- ### JSONPath Command with Output File Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Illustrates how to redirect the output of the `json path` command to a specified file. ```console $ json path -q "$.price_cap" -f /tmp/source.json -o result.json ``` -------------------------------- ### JSONPath Command Usage Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Demonstrates the basic usage of the `json path` command to query a JSON file using a JSONPath expression. ```console $ json path -q "$.price_cap" -f /tmp/source.json ``` -------------------------------- ### JSON Patch CLI Options Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Details the command-line options available for the `json patch` command, including input file, output file, and URI decoding. ```APIDOC json patch [-h] [-f FILE] [-o OUTPUT] [-u] PATCH Arguments: PATCH The patch document. This can be a file path to a JSON Patch document or a hyphen (-), which means the patch document will be read from the standard input stream. -h, --help show this help message and exit -f FILE, --file FILE The path to a file containing the target JSON document. If omitted or a hyphen (-), the target JSON document will be read from the standard input stream. -o OUTPUT, --output OUTPUT The path to a file to write the resulting object to. If omitted or a hyphen (-) is given, results will be written to the standard output stream. -u, --uri-decode Enable URI decoding of the JSON Pointer. In this example, we would look for a property called "hello world" in the root of the target document. ``` -------------------------------- ### Output to File or Standard Output Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Specifies the path to a file for writing the output. If no path is provided or a hyphen is used, the output goes to standard output. ```console $ json patch /tmp/patch.json -f /tmp/target.json -o result.json ``` ```console $ json patch /tmp/patch.json -f /tmp/target.json --output result.json ``` -------------------------------- ### JSONPath Selectors Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/custom_api.md Placeholder for documentation related to JSONPath selectors. ```python ## jsonpath.selectors.JSONPathSelector TODO: ``` -------------------------------- ### Pretty Printing JSON Output Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Compares the output of the `json pointer` command with and without the `--pretty` option, showing the difference in JSON formatting. ```console $ json --pretty pointer -p "/categories/1/products/0" -f /tmp/source.json { "title": "Cap", "description": "Baseball cap", "price": 15.0 } ``` -------------------------------- ### Using Query.take() Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/query.md Demonstrates the `take()` method, which returns a new Query instance for the next N matches, leaving the original iterator ready to resume. ```python from jsonpath import query it = query("$.some.*", {"some": [0, 1, 2, 3]}) for match in it.take(2): print(match.value) # 0, 1 for value in it.values(): print(value) # 2, 3 ``` -------------------------------- ### JSONPath Parser Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/custom_api.md Placeholder for documentation related to the JSONPath parser. ```python ## jsonpath.parse.Parser TODO: ``` -------------------------------- ### JSONPath Command with Query File Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Shows how to use the `json path` command with a JSONPath expression stored in a separate file. ```console $ json path -r /tmp/path.txt -f /tmp/source.json ``` -------------------------------- ### JSONPatch API Reference Source: https://github.com/jg-rp/python-jsonpath/blob/main/README.md Provides an overview of the JSONPatch API, specifically the `apply` function, detailing its parameters and expected behavior. ```APIDOC JSONPatch: apply(patch: list[dict], data: dict) -> dict Applies a list of JSON Patch operations to the provided data. Parameters: patch: A list of dictionaries, where each dictionary represents a JSON Patch operation (e.g., {"op": "add", "path": "/foo", "value": "bar"}). data: The target JSON data structure (dictionary) to which the patch operations will be applied. Returns: The modified data dictionary after applying all patch operations. Raises: jsonpatch.JsonPatchException: If any of the patch operations fail or are invalid. ``` -------------------------------- ### JSONPath Token Stream Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/custom_api.md Placeholder for documentation related to the JSONPath token stream. ```python ## jsonpath.stream.TokenStream TODO: ``` -------------------------------- ### Debug Mode: JSONPath Syntax Error Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Demonstrates how the `--debug` option provides a detailed stack trace when a JSONPath syntax error occurs, compared to the default short error message. ```console $ json --debug path -q "$.1" -f /tmp/source.json Traceback (most recent call last): File "/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/bin/json", line 8, in sys.exit(main()) File "/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/cli.py", line 338, in main args.func(args) File "/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/cli.py", line 234, in handle_path_command path = jsonpath.compile(args.query or args.path_file.read()) File "/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/env.py", line 148, in compile _path: Union[JSONPath, CompoundJSONPath] = JSONPath( File "/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/path.py", line 49, in __init__ self.selectors = tuple(selectors) File "/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/parse.py", line 256, in parse raise JSONPathSyntaxError(jsonpath.exceptions.JSONPathSyntaxError: unexpected token '1', line 1, column 2 ``` -------------------------------- ### JSON Patch Command Usage Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Illustrates the basic usage of the `json patch` command to apply a JSON Patch from a file to a target JSON document. ```console $ json patch /tmp/patch.json -f /tmp/target.json ``` -------------------------------- ### JSON Pointer API Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/pointers.md Provides an overview of the JSON Pointer class and its core methods for navigating JSON documents. ```APIDOC JSONPointer: __init__(pointer: str) Initializes a JSON Pointer object. resolve(data: Union[str, Mapping, Sequence]) -> Any Resolves the pointer against the provided JSON data. Parameters: data: JSON data as a string, file-like object, Mapping, or Sequence. Returns: The value at the pointer's location. resolve_parent(data: Union[str, Mapping, Sequence]) -> Tuple[Optional[Union[Mapping, Sequence]], Any] Resolves the pointer and returns the parent object and the target object. Returns (parent, object) or (parent, UNDEFINED) if object does not exist. exists(data: Union[str, Mapping, Sequence]) -> bool Checks if the pointer can be resolved against the data. join(*parts: str) -> JSONPointer Joins the current pointer with additional pointer parts. Extensions: - Keys Selector (`.~` or `[~]`): Targets object keys instead of values. - Key/Index Pointers (`#`): Represents keys or indices themselves, not their values. ``` -------------------------------- ### Joining JSON Pointers Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/pointers.md Illustrates the `join` method for concatenating JSON Pointers, showing how multiple parts can be combined. ```python from jsonpath import JSONPointer pointer = JSONPointer("/foo/bar") print(pointer) # /foo/bar print(pointer.join("baz")) # /foo/bar/baz print(pointer.join("baz", "0")) # /foo/bar/baz/0 ``` -------------------------------- ### Select Title and Price from Products Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/query.md Demonstrates how to use the `select` method to extract only the 'title' and 'price' fields from each product in a JSON structure. This is useful for creating targeted data views. ```python from jsonpath import query data = { "categories": [ { "name": "footwear", "products": [ { "title": "Trainers", "description": "Fashionable trainers.", "price": 89.99, }, { "title": "Barefoot Trainers", "description": "Running trainers.", "price": 130.00, "social": {"likes": 12, "shares": 7}, }, ], }, { "name": "headwear", "products": [ { "title": "Cap", "description": "Baseball cap", "price": 15.00, }, { "title": "Beanie", "description": "Winter running hat.", "price": 9.00, }, ], }, ], "price_cap": 10, } for product in query("$..products.*", data).select("title", "price"): print(product) ``` -------------------------------- ### JSON Pointer Command with URI Decoding Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/cli.md Shows how to enable URI decoding for JSON Pointers, allowing for special characters in pointer paths. ```console $ json pointer -p "/hello%20world" -f /tmp/source.json -u ``` -------------------------------- ### Converting Query Iterator to List Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/query.md Shows how to convert the query iterator to a list to allow for multiple iterations or manipulations, such as accessing elements by index. ```python from jsonpath import query # data = ... values = list( query("$.some[?@.thing]", data) .skip(5) .limit(10) .values() ) print(values[1]) ``` -------------------------------- ### JSONPointer to() Method for Relative Navigation Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/pointers.md Creates a new JSONPointer relative to the current pointer using a RelativeJSONPointer instance or string. Requires version 0.9.0 or later. Supports resolving values from data structures. ```python from jsonpath import JSONPointer data = {"foo": {"bar": [1, 2, 3], "baz": [4, 5, 6]}} pointer = JSONPointer("/foo/bar/2") print(pointer.resolve(data)) # 3 print(pointer.to("0-1").resolve(data)) # 2 print(pointer.to("2/baz/2").resolve(data)) # 6 ``` ```python from jsonpath import JSONPointer from jsonpath import RelativeJSONPointer data = {"foo": {"bar": [1, 2, 3], "baz": [4, 5, 6], "some": "thing"}} some_pointer = JSONPointer("/foo/bar/0") another_pointer = JSONPointer("/foo/baz/2") rel = RelativeJSONPointer("2/some") print(rel.to(some_pointer).resolve(data)) # thing print(rel.to(another_pointer).resolve(data)) # thing ``` -------------------------------- ### JSONPath Library Exceptions Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/exceptions.md This section lists the core exceptions provided by the JSONPath library. Each exception inherits from JSONPathError and provides a 'token' attribute for detailed error context. ```APIDOC JSONPathError: Description: Base exception for all JSONPath related errors. Properties: token: The Token object that caused the error. JSONPathSyntaxError: Inherits from: JSONPathError Description: Raised when the JSONPath expression has a syntax error. JSONPathTypeError: Inherits from: JSONPathError Description: Raised when an operation is performed on an incompatible data type. JSONPathIndexError: Inherits from: JSONPathError Description: Raised when an index is out of bounds. JSONPathNameError: Inherits from: JSONPathError Description: Raised when a property or key name is not found. JSONPointerError: Inherits from: JSONPathError Description: Base exception for JSON Pointer related errors. JSONPointerResolutionError: Inherits from: JSONPointerError Description: Raised when a JSON Pointer cannot be resolved. JSONPointerIndexError: Inherits from: JSONPointerError Description: Raised when a JSON Pointer index is out of bounds. JSONPointerKeyError: Inherits from: JSONPointerError Description: Raised when a JSON Pointer key is not found. JSONPointerTypeError: Inherits from: JSONPointerError Description: Raised when a JSON Pointer operation involves an incompatible type. RelativeJSONPointerError: Inherits from: JSONPathError Description: Base exception for Relative JSON Pointer related errors. RelativeJSONPointerIndexError: Inherits from: RelativeJSONPointerError Description: Raised when a Relative JSON Pointer index is out of bounds. RelativeJSONPointerSyntaxError: Inherits from: RelativeJSONPointerError Description: Raised when a Relative JSON Pointer has a syntax error. JSONPatchError: Inherits from: JSONPathError Description: Base exception for JSON Patch related errors. JSONPatchTestFailure: Inherits from: JSONPatchError Description: Raised when a JSON Patch 'test' operation fails. ``` -------------------------------- ### Basic Query Iterator Usage Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/query.md Demonstrates how to use the query iterator to skip the first five matches, limit the total number of matches to ten, and then retrieve the values of each match. ```python from jsonpath import query # data = ... values = ( query("$.some[?@.thing]", data) .skip(5) .limit(10) .values() ) for value in values: # ... ``` -------------------------------- ### Query Iterator Chainable Methods Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/query.md Illustrates the chainable methods available on Query objects, including skip, limit, and tail, which allow for sequential manipulation of the match iterator. ```APIDOC Query Methods: Chainable Methods (return self): skip(n: int) | drop: Drop up to n matches from the iterator. limit(n: int) | head, first: Yield at most n matches from the iterator. tail(n: int) | last: Drop matches from the iterator up to the last n. Terminal Methods (cannot be chained): values(): Return an iterable of objects for each match. locations(): Return an iterable of normalized paths for each match. items(): Return an iterable of (object, normalized path) tuples for each match. pointers(): Return an iterable of JSONPointer instances for each match. first_one() | one: Return the first JSONPathMatch or None. last_one(): Return the last JSONPathMatch or None. ``` -------------------------------- ### Using Filter Context Variables Source: https://github.com/jg-rp/python-jsonpath/blob/main/docs/advanced.md Demonstrates how to pass arbitrary variables into filter expressions using the `filter_context` argument in `findall()`. This allows for dynamic filtering based on external values, such as a limit. ```python import jsonpath data = { "users": [ { "name": "Sue", "score": 100, }, { "name": "John", "score": 86, }, { "name": "Sally", "score": 84, }, { "name": "Jane", "score": 55, }, ] } user_names = jsonpath.findall( "$.users[?@.score < _.limit].name", data, filter_context={"limit": 100}, ) ```