Search code examples
jsonrest-assuredrest-assured-jsonpath

Filtering on nested JSON array: Rest Assured


I am trying to filter my GET response(JSON) based on a value in a nested JSON array. For eg: In the following JSON i want to filter an JSON array and print the names of cakes using Chocolate as batter.

{
"id": "0001",
"type": "donut",
"name": "Choco Blueberry Cake",
"ppu": 0.55,
"batter":[
         { "id": "1001", "type": "Regular" },
         { "id": "1002", "type": "Chocolate" },
         { "id": "1003", "type": "Blueberry" }
 ]
}

I have tried something like:

List<String> chocolateCakeList =jsonPath.getList("findAll{it.batter.type=='chocolate'}.name");

and

List<String> chocolateCakeList =jsonPath.getList("findAll{it.batter.it.type=='chocolate'}.name");

Both return empty Lists.


Solution

  • Problem

    1. First, if you want to use findAll then the object to be axtract must be an array. Your json is object {}, not an array []. Actually, your nested object batter is an array [].

    2. keyword to search is Chocolate, not chocolate. Case-sensitive is applied here.

    Solution

    -If your whole response is exactly what you posted, then the path to extract is

    String name = jsonPath.getString("name")
    

    -If your response has structrure like this.

    [
      {
        "id": "0001",
        "type": "donut",
        "name": "Choco Blueberry Cake",
        "ppu": 0.55,
        "batter": [
          {
            "id": "1001",
            "type": "Regular"
          },
          {
            "id": "1002",
            "type": "Chocolate"
          },
          {
            "id": "1003",
            "type": "Blueberry"
          }
        ]
      },
      {
        "id": "0002",
        "type": "donut",
        "name": "Choco Blueberry Cake",
        "ppu": 0.55,
        "batter": [
          {
            "id": "1001",
            "type": "Regular"
          },
          {
            "id": "1002",
            "type": "Chocolate 2"
          },
          {
            "id": "1003",
            "type": "Blueberry"
          }
        ]
      }
    ]
    

    Then the extraction is

    List<String> list = jsonPath.getList("findAll {it.batter.findAll {it.type == 'Chocolate'}}.name");