Search code examples
javajsonpath

JsonPath / Java how to apply Data Type conversion in Filtering


I'm using JsonPath java library https://github.com/json-path/JsonPath

So far, everything works as expected. There is only one issue I'm trying to solve, but I don't see any function the library provides to support the case.

Technically, I have a Json response data like below

{
    "data":[
        {
            "start_time": "2021-01-26T11:36:10-0800",
            "insights": {
                "data": [
                    {
                        "account_id": "104448579711490",
                        "campaign_id": "6230174444738",
                        "adset_id": "6230236298338",
                        "date_start": "2021-01-12",
                        "date_stop": "2021-02-10",
                        "impressions": "81619",
                        "spend": "33.54"
                    }
                ],
                "paging": {
                    "cursors": {
                        "before": "MAZDZD",
                        "after": "MAZDZD"
                    }
                }
            },
            "id": "6230236298338"
        }
    ]
}

If you observe, the value under impressions is STRING type, not INTEGER or LONG type. Thus, the current JsonPath setting I'm using in order to pick up the data isn't working as expected

$.data[?(@.insights && @.insights.data && @.insights.data[0].impressions > 0)]

However, it works well on some Jsonpath testing sites like https://jsonpath.com/

I'm looking for a function that can help to let JsonPath can understand the condition in the filtering and automatically convert the value under impressions to INTEGER or LONG. Maybe it's a bug of the lib, I'm going to look into the code and see if I can improve it or not.

Please let me know if you have any workaround to make the setting above work as expected. Really appreciate your information here.

UPDATE @wp78de suggests a trick that works for the case. Thank you.

$.data[?(@.insights && @.insights.data && @.insights.data[0].impressions > '0')]

Solution

  • First, it doesn't make a lot of sense, but providing the comparison value as string does the trick:

    $.data[?(@.insights && @.insights.data && @.insights.data[0].impressions > '0')] 
    

    I verified this in coded and tested it with Jayway JsonPath Evaluator implementation online. So, the library converts the value internally to the right type to make the comparison work.