Search code examples
groovyrest-assuredgpath

Rest Assured Groovy GPath filtering out result


I am trying to return the value of "description" in "dependentPreferences" where the response meets two conditions: First, check if the name is "John Smith" and then check if the "image" in preferences equals to "papaya.jpg".

The response body is as follows:

[    
    {
        "id": 1,
        "name": "John Smith",
        "description": null,
        "shortDescription": "No recorded interests.",
        "alias": "JS",
        "preferences": [
            {
                "id": 1,
                "description": "likes candy and papaya",
                "image": "papaya.jpg",
                "name": "Papaya",
                "dependentPreferences": [
                    {
                        "id": 1,
                        "description": "Fruit must be ripe",
                        "image": "ripe-papaya.jpg",
                        "name": "pap"
                    }
                ]
            }
         ]
    },
    {
        "id": 2,
        "name": "Jane Smith",
        "description": null,
        "shortDescription": "No recorded interests.",
        "alias": "JS",
        "preferences": [
            {
                "id": 1,
                "description": "likes candy and papaya",
                "image": "papaya.jpg",
                "name": "Papaya",
                "dependentPreferences": [
                    {
                        "id": 1,
                        "description": "Candy must be Skittles",
                        "image": "Skittles.jpg",
                        "name": "skt"
                    }
                ]
            }
         ]
    }
]

So far, i have tried something like this:

response.jsonPath().getString("find { it.name == 'John Smith' }.preferences.find {it.image == 'papaya.jpg'}.dependentPreferences.description 

but it is complaining about the syntax. I know this portion of the code works to find the image:

response.jsonPath().getString("find { it.name == 'John Smith' }.preferences.image

but i am having trouble constructing the second condition. Any help would be appreciated.


Solution

  • Working example here. This works for me:

    def endpoint = "http://localhost:3130/ids.json"
    def jsonResponse = get(endpoint).then().contentType(ContentType.JSON).extract().response()
    def path = jsonResponse.jsonPath()
    
    def result = path.getString("find { it.name == 'John Smith' }.preferences.find {it.image == 'papaya.jpg'}.dependentPreferences.description")
    

    Though to be honest: in the JSON, dependentPreferences is an array of objects, so there is a chance for error if the data is different than presented.