Search code examples
javajsonrest-assuredjsonpathrest-assured-jsonpath

RestAssured - JsonPath filter a matching Object's properties from an array of objects, given a filter criteria


I am writing an integration test to my microservice using rest assured. I have a Json payload like this which is returned from it.

{
   "sessionQuestions":[
      {
         "id":1272,
         "sessionId":1146,
         "questionId":"1002",
      },
      {
         "id":1273,
         "sessionId":1146,
         "questionId":"1004",
      }
   ]
}

I need to find the id of a sessionquestion given the questionId value. Then I need to compare them in my assertion. I am having hard time fetching the id off of a sessionQuestion given the questionId value. I am using JsonPath to get this thing done. And here's my Json path expression.

new JsonPath(response).get("$.sessionQuestions[?(@.questionId=='1002')].id");

This throws an error.

java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found '[' @ line 1, column 45.
   nRootObject.$.sessionQuestions[?(@.quest
                                 ^

1 error

   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

I tried the same Json path expression in this online evaluator, which works fine. I am using json-path-2.9.0.jar

What I am doing wrong here? Any help is really appreciated.


Solution

  • Which version of JsonPath do you use? I use this.

    And the code which works for your case is:

    JsonPath.parse(response).read("$.sessionQuestions[?(@.questionId=='1002')].id").toString();
    

    And try with this JSON:

    {
       "sessionQuestions":[
          {
             "id":1272,
             "sessionId":1146,
             "questionId":"1002"
          },
          {
             "id":1273,
             "sessionId":1146,
             "questionId":"1004"
          }
       ]
    }
    

    Edit: If you are using this dependancy (json-path-2.9.0), you have to do it like this:

    from(response).getList("sessionQuestions.findAll { it.questionId=='1002' }.id").toString();
    

    and you have to import from like this:

    import static com.jayway.restassured.path.json.JsonPath.from;