jmespath.py

repository·develop·Indexed 23 days ago

https://github.com/jmespath/jmespath.py

A Python implementation of JMESPath, a declarative query language for JSON documents. It provides the jmespath.search() and jmespath.compile() functions for extracting elements from data structures, the jmespath.Options class for configuring evaluation behavior, and the jp.py CLI tool for executing queries against JSON data.

Tokens
971
Snippets
3
Records
9
Agent score
32%

What's inside jmespath.py

  1. Create custom JMESPath functions

    develop

    You can extend JMESPath by adding custom functions. Note that this support is currently experimental. To implement custom functions, follow these steps:

    1. Create a subclass of jmespath.functions.Functions.
    2. Define methods following the naming convention _func_<name>.
    3. Decorate these methods with @jmespath.functions.signature to specify expected argument types.
    4. Pass an instance of your subclass to the custom_functions argument in a jmespath.Options object.
    5. Provide that Options instance to your search call.
    import jmespath
    from jmespath import functions
    
    class CustomFunctions(functions.Functions):
        @functions.signature({'types': ['string']})
        def _func_unique_letters(self, s):
            return ''.join(sorted(set(s)))
    
        @functions.signature({'types': ['number']}, {'types': ['number']})
        def _func_my_add(self, x, y):
            return x + y
    
    options = jmespath.Options(custom_functions=CustomFunctions())
    
    # Using the custom 'my_add' function
    print(jmespath.search('my_add(`1`, `2`)', {}, options=options))
    
    # Using the custom 'unique_letters' function
    print(jmespath.search('foo.bar | unique_letters(@)', {'foo': {'bar': 'ccbbadd'}}, options=options))
  2. Configure evaluation behavior with jmespath.Options

    develop
    You can pass an instance of jmespath.Options to search or a compiled expression to control how the expression is evaluated. For example, to ensure dictionary keys are returned in a specific order (e.g., using collections.OrderedDict), use the dict_cls option.
  3. Perform a JMESPath search with jmespath.search()

    develop

    Use jmespath.search(expression, data) to extract elements from a Python data structure using a JMESPath expression.

    import jmespath
    path = jmespath.search('foo.bar', {'foo': {'bar': 'baz'}})
    # Returns 'baz'
  4. Compile JMESPath expressions with jmespath.compile()

    develop
    To optimize repeated searches on different documents using the same expression, use jmespath.compile(expression). This returns a parsed expression object that you can call .search() on repeatedly, avoiding the overhead of re-parsing the expression each time.
  5. Handle jp.py CLI error outputs

    develop

    When a query fails, jp.py catches specific JMESPath exceptions and maps them to the following error prefixes on stderr:

    • invalid-arity: <error_message> (from exceptions.ArityError)
    • invalid-type: <error_message> (from exceptions.JMESPathTypeError)
    • unknown-function: <error_message> (from exceptions.UnknownFunctionError)
    • syntax-error: <error_message> (from exceptions.ParseError)
  6. Inspect the Abstract Syntax Tree (AST) with --ast

    develop
    If you need to debug an expression or see how it is parsed, use the --ast flag. This mode will compile the expression and print its parsed Abstract Syntax Tree (AST) using pretty-printing, without attempting to search any data.
  7. Use the jp.py CLI to execute JMESPath queries

    develop
    The jp.py CLI tool allows you to run JMESPath expressions against JSON data provided via a file or standard input (stdin). The tool outputs the resulting JSON to stdout. If the expression is invalid or encounters a runtime error, it prints a specific error prefix to stderr and exits with code 1.