jmespath.js icon indicating copy to clipboard operation
jmespath.js copied to clipboard

Support custom functions

Open the-g-man opened this issue 7 years ago • 3 comments

Is there a timeframe for support for adding our own custom functions - as is already available in jmespath.py?

If this isn't in the pipeline, would you be willing to take a PR for adding this? I'd propose an interface as close as possible to the one already available in Python. So...

> jmespath.search(query, data, { customFunctions : new MyCustomFunctions() })

the-g-man avatar May 04 '17 22:05 the-g-man

Looks like @burningtree created PR for this a while ago: https://github.com/jmespath/jmespath.js/pull/2

bejohu avatar Apr 28 '19 14:04 bejohu

+1

peterfotinis avatar May 30 '19 06:05 peterfotinis

We've implemented this in a slightly different way while still maintaining validation and interpreter scoping within the function. It also helps to add any number as a series of plugins to jmespath. See https://github.com/nanoporetech/jmespath-ts

Here's a snippet from the unit test:

  it('register a customFunction', () =>  {
      expect(() => search({
        foo: 60,
        bar: 10
      }, 'divide(foo, bar)')
      ).toThrow('Unknown function: divide()');


      jmespath.registerFunction('divide', function(resolvedArgs) {
          const [dividend, divisor] = resolvedArgs;
          return dividend / divisor;
        },
        [{ types: [jmespath.TYPE_NUMBER] }, { types: [jmespath.TYPE_NUMBER] }]
      )

      expect(search({
        foo: 60,
        bar: 10
      }, 'divide(foo, bar)')
      ).toEqual(6)
  });

glenveegee avatar May 14 '20 19:05 glenveegee