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

Add support for custom functions.

Open burningtree opened this issue 10 years ago • 1 comments

Allow to use custom functions via resolveUnknownFunction handler:

var jmespath = require('jmespath');
var struct = { group: { id: 1, name: "steve" }};
var options = {
  resolveUnknownFunction: function(fn, args, runtime){
    return args[0].name + " is best";
  }
};
var output = jmespath.search(struct, "example(group)", options);
console.log(output);

Output is:

"steve is best"

burningtree avatar Mar 17 '15 08:03 burningtree

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 12 '20 21:05 glenveegee