javajsonpathjayway

How to combine two attribute from a json to create json predicate with in clause in Java?


I have a json as below

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95,
               "version": 1
            },
            {
                "category": "reference",
                "author": "Nigel Reas",
                "title": "Sayings of the Decade",
                "price": 8.96,
               "version": 2
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99,
                "version": 1
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99,
                "version": 2
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99,
                "version": 3
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

Now i want to filter the json based on two attributes.

for example: $.store.book[?((@.category,@.version) in [('fiction',2),('reference',1)])]

But above predicate is not working. Is there any way to achieve that?


Solution

  • The syntax you showed does not look correct. As far as I understand the JayWay implementation (yes, this comes down to the implementation details of the library), you sequentially need to combine filters using && and || like this:

    $.store.book[?(@.category=='fiction' && @.version=='1' || @.category=='reference' && @.version=='2')]
    

    First, I tried to r create a combined filter using in, but this seems to select more values than you want:

    $.store.book[?(@.category in  ['fiction','reference'] && @.version in  ['1','2'])]