Skip to content

Commit 2faa881

Browse files
committed
added test and updated readme
1 parent d498175 commit 2faa881

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,46 @@ check out the [JMESPath libraries page](http://jmespath.org/libraries.html).
5555

5656
And finally, the full JMESPath specification can be found
5757
on the [JMESPath site](http://jmespath.org/specification.html).
58+
59+
## Custom Filter Functions
60+
61+
As an extension to common JMESPath API and available in jmespath.js only,
62+
custom filter functions can be specified through the ``functionTable``
63+
property of the optional third argument of the ``search`` function.
64+
The custom functions can even call third-party
65+
libraries via closure. The following example shows how a custom
66+
filter function `contains_ci` is implemented with
67+
[`lodash`](https://lodash.com/) library
68+
to provide case insensitive string matching
69+
70+
```
71+
const jmespath = require('jmespath')
72+
const assert = require('assert')
73+
const _ = require('lodash')
74+
let res = jmespath.search([{ a: 'foo' }], "[?contains_ci(a, 'FOO')]", {
75+
functionTable: {
76+
/*jshint camelcase: false */
77+
contains_ci: {
78+
_func: function(resolvedArgs) {
79+
if (!resolvedArgs[0] || !resolvedArgs[1]) {
80+
return false
81+
}
82+
return (
83+
_.toLower(resolvedArgs[0]).indexOf(_.toLower(resolvedArgs[1])) >= 0
84+
)
85+
},
86+
_signature: [
87+
{
88+
types: [2]
89+
},
90+
{
91+
types: [2]
92+
}
93+
]
94+
}
95+
}
96+
})
97+
assert.deepStrictEqual(res, [{ a: 'foo' }])
98+
```
99+
100+
See [type constants](https://github.com/jmespath/jmespath.js/blob/master/jmespath.js#L132) for type mapping used by the example.

test/jmespath.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,4 +231,36 @@ describe('search', function() {
231231
}
232232
}
233233
);
234+
235+
it('should allow specify and use custom function', function() {
236+
var res
237+
try {
238+
res = jmespath.search([{ a: 'foo' }], "[?contains_ci(a, 'FOO')]", {
239+
functionTable: {
240+
/*jshint camelcase: false */
241+
contains_ci: {
242+
_func: function(resolvedArgs) {
243+
if (!resolvedArgs[0] || !resolvedArgs[1]) {
244+
return false
245+
}
246+
return (
247+
resolvedArgs[0]
248+
.toLowerCase()
249+
.indexOf(resolvedArgs[1].toLowerCase()) >= 0
250+
)
251+
},
252+
_signature: [
253+
{
254+
types: [2]
255+
},
256+
{
257+
types: [2]
258+
}
259+
]
260+
}
261+
}
262+
})
263+
} catch (e) {}
264+
assert.deepStrictEqual(res, [{ a: 'foo' }])
265+
})
234266
});

0 commit comments

Comments
 (0)