简体   繁体   中英

jsonpath predicate filter not working in java

I am using com.jayway.jsonpath 2.2.0 to see if attributes are in a series of JSON records.

Here's an example of a JSON record being used

{
    "data": 
    {
        "sampleTime": "2017-06-02T11:47:37.040Z",
        "target": 
        {
            "gateway": "TEST1",
            "probe": "zeus",
            "managedEntity": "zeus",
            "type": "",
            "sampler": "HARDWARE",
            "dataview": "HARDWARE",
            "filter": 
            {
                "osType": "Linux",
                "pluginName": "HARDWARE"
            }
        },

        "name": "cpuUtilisation",
        "row": 
        {
            "Value": "50.39 % (average load)"
        }
    },

    "operation": "update"
}

So I want to match if osType == 'Linux', see in the above record

I have some code that tries to do this and seems to work

@Test
public void test_jsonpath_filter_find_match() throws Exception {

    // load in json record from file
    String jsonString = FileUtils.readFileToString(new File("resources/geneos-raw.table-cpuutilisation.json"), "UTF-8");

    List<Map<String, Object>> match  = JsonPath.parse(jsonString).read("$..filter", Filter.filter(Criteria.where("osType").eq("Linux")));

    System.out.println("result>" + match);
}

I get result printed that seems to prove the JSON record matches the filter

2017/06/03 09:01:27.216 [DEBUG][com.jayway.jsonpath.internal.path.CompiledPath]: Evaluating path: $..['filter']
result>[{"osType":"Linux","pluginName":"HARDWARE"}]

However, if I put a non-matching filter I still get the same result.

Note the osType == 'Windows' in the filter

@Test
public void test_jsonpath_filter_find_match() throws Exception {

    // load in json record from file
    String jsonString = FileUtils.readFileToString(new File("resources/geneos-raw.table-cpuutilisation.json"), "UTF-8");

    List<Map<String, Object>> match  = JsonPath.parse(jsonString).read("$..filter", Filter.filter(Criteria.where("osType").eq("Windows")));

    System.out.println("result>" + match);
}

And the result is a match!

2017/06/03 09:02:06.137 [DEBUG][com.jayway.jsonpath.internal.path.CompiledPath]: Evaluating path: $..['filter']
result>[{"osType":"Linux","pluginName":"HARDWARE"}]

I believe the result should have been an empty List returned.

Is this a bug, or is there a flaw in my code/thinking?

Try filtering like this:

JsonPath.parse(jsonString).read("$..filter[?(@.osType=='Windows')]");
JsonPath.parse(jsonString).read("$..filter[?(@.osType=='Linux')]");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM