JsonPath Fetch string after filter

1k Views Asked by At

I am using Jayway JsonPath 2.2 version in JAVA. I have few questions on the same.

Sample JSON:

{ "l5": [ { "type": "type1", "result": [ "res1" ] }, { "type": "type2", "result": [ "r1" ] } ] }

  1. I want to fetch a string after a filter is applied?

    Eg:

    Path used to fetch a string is l5[?(@.type == 'type2')].type Expected result: type2 (string), but getting ["type2"] (array)

    Please correct the path if i am doing anything wrong to fetch it as a string?

  2. Unable to index the resultant array after the filter is applied. How can i achieve the same?

    Eg:

    If i use the path l5[?(@.type == 'type2')][0], instead of returning me the first JSONObject it returns []

  3. Is it possible to extract substring from a string using jsonPath?

    Something like l5[0].type[0,2] => res

Note: I cannot do any operation in JAVA, as i wanted to keep the library generic?

1

There are 1 best solutions below

2
Amit Bhati On

The return value of jsonPath is always an array, quoted from here.

So, the operation1 you are trying is not possible i.e. String value will never be returned.
Even operation 2 and operation 3 doesn't look feasible with jayway jsonpath.

Good read on jayway Jsonpath.

Only Possible way for operation 1 and 2 looks something like below:-

String jsonpath="l5[?(@.type == 'type2')].type";
        DocumentContext jsonContext = JsonPath.parse(jsonString);
        List<String> typeDataList= jsonContext.read(jsonpath);
        System.out.println(typeDataList.get(0)); //type2