Create custom JMESPath functions
developYou can extend JMESPath by adding custom functions. Note that this support is currently experimental. To implement custom functions, follow these steps:
- Create a subclass of
jmespath.functions.Functions. - Define methods following the naming convention
_func_<name>. - Decorate these methods with
@jmespath.functions.signatureto specify expected argument types. - Pass an instance of your subclass to the
custom_functionsargument in ajmespath.Optionsobject. - Provide that
Optionsinstance to yoursearchcall.
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))