Search code examples
jsonjsonpath

How to apply filter AND select top most matches in JSONPath


I want to filter by some expression and select only the first five matches to that expression.

http://goessner.net/articles/JsonPath/ shows how to do a filter on a value:

$..book[?(@.price<10)]

And how to filter out only the first matches:

$..book[:2]

But how do I combine the two? I've tried various approaches, but cant seem to find anything that works.


Solution

  • In jsonpath-plus, this can be retrieved by:

    var result = JSONPath({json: sample, path: '$..book[?(@property <= 5 && @.price<10)]'});
    

    This is because @property here is a custom feature of jsonpath-plus for getting the current object property, in this case, the array index.

    JSFiddle

    I think the original JSONPath spec, while a great start, was somewhat under-specified, which is why it was enhanced and has been better documented at https://github.com/s3u/JSONPath . However, there are other implementations, at least in other languages, so there may be some discrepancies in how this can be done (if at all) in other implementations.

    (Disclaimer: I'm involved with the jsonpath-plus project.)