0

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.

kokodee
  • 285
  • 1
  • 3
  • 15

1 Answers1

1

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.

Michael Easter
  • 23,733
  • 7
  • 76
  • 107
  • Thanks! Actually, even though your result answer was exactly like mine, your comment gave me a hint to see exactly why my code was failing. In my case, i didn't always have a value in image. Swapping with a static key and value, helped me resolve the issue. – kokodee Oct 30 '20 at 02:17