Skip to content

Commit

Permalink
added test and updated readme
Browse files Browse the repository at this point in the history
  • Loading branch information
f-w committed Aug 7, 2017
1 parent d498175 commit 2faa881
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,46 @@ check out the [JMESPath libraries page](http://jmespath.org/libraries.html).

And finally, the full JMESPath specification can be found
on the [JMESPath site](http://jmespath.org/specification.html).

## Custom Filter Functions

As an extension to common JMESPath API and available in jmespath.js only,
custom filter functions can be specified through the ``functionTable``
property of the optional third argument of the ``search`` function.
The custom functions can even call third-party
libraries via closure. The following example shows how a custom
filter function `contains_ci` is implemented with
[`lodash`](https://lodash.com/) library
to provide case insensitive string matching

```
const jmespath = require('jmespath')
const assert = require('assert')
const _ = require('lodash')
let res = jmespath.search([{ a: 'foo' }], "[?contains_ci(a, 'FOO')]", {
functionTable: {
/*jshint camelcase: false */
contains_ci: {
_func: function(resolvedArgs) {
if (!resolvedArgs[0] || !resolvedArgs[1]) {
return false
}
return (
_.toLower(resolvedArgs[0]).indexOf(_.toLower(resolvedArgs[1])) >= 0
)
},
_signature: [
{
types: [2]
},
{
types: [2]
}
]
}
}
})
assert.deepStrictEqual(res, [{ a: 'foo' }])
```

See [type constants](https://github.com/jmespath/jmespath.js/blob/master/jmespath.js#L132) for type mapping used by the example.
32 changes: 32 additions & 0 deletions test/jmespath.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,4 +231,36 @@ describe('search', function() {
}
}
);

it('should allow specify and use custom function', function() {
var res
try {
res = jmespath.search([{ a: 'foo' }], "[?contains_ci(a, 'FOO')]", {
functionTable: {
/*jshint camelcase: false */
contains_ci: {
_func: function(resolvedArgs) {
if (!resolvedArgs[0] || !resolvedArgs[1]) {
return false
}
return (
resolvedArgs[0]
.toLowerCase()
.indexOf(resolvedArgs[1].toLowerCase()) >= 0
)
},
_signature: [
{
types: [2]
},
{
types: [2]
}
]
}
}
})
} catch (e) {}
assert.deepStrictEqual(res, [{ a: 'foo' }])
})
});

0 comments on commit 2faa881

Please sign in to comment.