Search code examples
jsonkarate

Extract json object from the response in karate framework


From the following JSON response of an API call:

{ 
   "status":200,
   "data":[ 
      { 
         "items":[ 
            { 
               "type":"Notification",
               "content":{ 
                  "message":"Welcome to ACME",
                  "id":"66d93f00-4d74-11ea-9c63-6f69f79cca26",
                  "args":{ 
                     "freezeTimeline":false,
                     "month":0
                  },
                  "timelineButtonText":null
               }
            },
            { 
               "type":"Notification",
               "content":{ 
                  "message":"ACME is a small account.",
                  "id":"670928a0-4d74-11ea-9c63-6f69f79cca26",
                  "args":{ 
                     "freezeTimeline":false,
                     "month":0
                  },
                  "timelineButtonText":null
               }
            },
            { 
               "type":"Event",
               "content":{ 
                  "id":"e08ea760-5b4a-45d2-888e-4a5c8ef5bf1f"
               }
            },
            { 
               "type":"Event",
               "content":{ 
                  "id":"77b0c588-36be-4821-8d26-8c374c29a899"
               }
            },
            { 
               "type":"Event",
               "content":{ 
                  "id":"9fd74f9c-4d50-445b-94f0-37d21e53bdae"
               }
            }
         ],
         "move":{ 
            "Month":1,
            "Year":1,
            "Quarter":1
         }
      }
   ]
}

Inside Items array, There are 3 items of type=Event How can I get the content.id of first event?

It works for me like with below code

And def eventId = response.data[0].items[4].content.id

But I want something like: if there is a type of event extract content.id of the same.


Solution

  • Do it in 2 steps, it will be easier to read / follow:

    Assuming the items array is in a variable:

    * def events = $items[?(@.type=='Event')]
    * def first = events[0].content.id
    * match first == 'e08ea760-5b4a-45d2-888e-4a5c8ef5bf1f'