javajsonpathjayway

How to compare number string in filter operator?


data: [
    {
        "name": "mark",
        "age": "20"
    },
    {
        "name": "john",
        "age": "10"
    }
]

in this case, how to get age greater than 10?

sample code:

JsonPath.read(json, "$.data[?(@.age > 10)]");

Solution

  • This can be done using Jayway's JsonPath library. First, the JSON you showed is not good for processing, the wrapping { } are missing. Second, Jayway's comparison operator works if you test against the number as a string (It's a bit weird but the library does the required casting internally that way).

    So, with this JSON:

    {
       "data":[
          {
             "name":"mark",
             "age":"20"
          },
          {
             "name":"john",
             "age":"10"
          }
       ]
    }
    

    And this filter:

    $.data[?(@.age > '10')]
    

    You get the expected result [{"name" : "mark", "age" : "20"}]. You can test it online here.

    Update

    As pointed out by Parveen Verma, the suggested filter will not work if the range filter requires an implicit type conversion.
    Jayway seems to only support implicit conversions when using the equality operators, e.g. $.data[?(@.age == 10)] (this works despite the type differences).

    There is an unmerged pull request that adds this behavior; since the code is somewhat behind the current version it may require some work to integrate it but if you really need this functionality it can be done.