Raj Kumar
Raj Kumar

Reputation: 51

Karate -- JSON Response Parsing

Below is the JSON response I receive when I am hitting a particular web service:

[
  {
    "sId" : "0001",
    "sName" : "abc1",
    "sPlace" : "abc11"
  }, {
    "sId" : "0002",
    "sName" : "abc2",
    "sPlace" : "abc12"
  }, {
    "sId" : "0003",
    "sName" : "abc3",
    "sPlace" : "abc13"
  }, {
    "sId" : "0004",
    "sName" : "abc4",
    "sPlace" : "abc14"
  }
]

I don't know which index has my expected values (I need to validate multiple values after identifying which has sId == '0003'), this is dynamic. Don't want to user hard coded value. And match response.[3].sId == '0003' because this will be changed next time.

I have two questions regarding this:

  1. How can I pass response to java code and get the array index which having sId == '0003' so that I can use this index to validate?
  2. How can I pass a variable value as an array index in response?

The code below is not working.

def ind = Java.type('karate.Utility.FindIndex') 
response.['#ind'].sId == '0003'

Upvotes: 3

Views: 9015

Answers (1)

Babu Sekaran
Babu Sekaran

Reputation: 4239

karate uses json-path which allows writing conditions to read data from JSON.

example:

* def sId = "0003"
* def sValue = karate.jsonPath(response, "$[?(@.sId == '" + sId + "')]")
* match sValue[0] == {"sId" : "0003","sName" : "abc3","sPlace" : "abc13"}

now if there is a match in sId on the response JSON array, all such matches will be returned.

No need to do * match sValue[0].sId == "0003" as this is your filter criteria

More about JSON path

online JSON path evaluator

karate doc refernce

Upvotes: 2

Related Questions