jmespath / jmespath.py

JMESPath is a query language for JSON.
http://jmespath.org
MIT License
2.19k stars 181 forks source link

Can I use map to do some calculation #154

Open ChenXiaoTemp opened 6 years ago

ChenXiaoTemp commented 6 years ago

User case:

[1,2,3]

What I want :

[2,3,4]

I have tried

map(&@+2,@)

it not works.

wjo1212 commented 6 years ago
import jmespath
from jmespath import functions

# 1. Create a subclass of functions.Functions.
#    The function.Functions base class has logic
#    that introspects all of its methods and automatically
#    registers your custom functions in its function table.
class CustomFunctions(functions.Functions):
    # Here's another example.  This is creating
    # a jmespath function called "my_add" that expects
    # two arguments, both of which should be of type number.
    @functions.signature({'types': ['number']}, {'types': ['number']})
    def _func_my_add(self, x, y):
        return x + y

# 4. Provide an instance of your subclass in a Options object.
options = jmespath.Options(custom_functions=CustomFunctions())

# this will yield [3,4,5]
print(
    jmespath.search(
        "map(&my_add(@, `2`), @)",
        [1,2,3],
        options=options
    )
)