Reputation: 77
I am trying to iterate over the array and need to compare each item of the array with the template I am creating from another Json response. This is the sample response I am getting. It is much larger and size of the array is dynamic.
* def actual =
"""
{ "id": "10103",
"city": "xxx",
"eq": "xxx",
"noOfSqt": "20000"
},
{ "id": "12394",
"city": "xxx",
"eq": "xxx",
"noOfSqt": "20000"
},
{ "id": "74747",
"city": "xxx",
"eq": "xxx",
"noOfSqt": "20000"
}
"""
From another json response I save ids in List. They are in a different order than the ids in"actual" array. Looks like that.
* def IDs = [12394, 74747, 10103]
This is my solution if I only have "actual" array of size 1, I am passing index 0. I get the first item from the IDs List, then retrieve the array item from "actual" array based on that ID.
* def i = 0 //index zero
* def index = IDs[i] //first item of the array at index 0 is 12394
* def firstObject = karate.jsonPath(actual, "$[?(@.id == '" + index + "')]")[0] //array object where id is 12394
* def city = karate.jsonPath(someOtherJson, "$.loc[?(@.newID == '" + index + "')].value")[0]
* def eq = karate.jsonPath(someOtherJson, "$.mix[?(@.newID == '" + index + "')]..value")[0]
* def noOfSqt = karate.jsonPath(someOtherJson, "$.flat[?(@.newID == '" + index + "')].value")[0]
* def expected =
"""
{
"city": "#(city)",
"eq": "#(eq)",
"noOfSqt": "#(noOfSqt)"
}
"""
* match firstObject contains expected
Instead of passing i = o ( index zero), please help me to iterate, so I can compare each item of the array. I have reviewed karate.repeat, karate.apendTo, karate.forEach(), JS loop, but still having issue implementing those. Also I am using contains instead == because the array and template have different number of attributes.
Upvotes: 1
Views: 322
Reputation: 58153
First, you can achieve what you want in one line (in Karate 1.0 for the JS array map instead of karate.map()
):
* match actual[*].id contains IDs.map(x => x + '')
I leave it as an exercise to you to figure out how that works.
Sometimes it is perfectly ok to convert your existing JSON to another "shape" using JsonPath expressions or karate.map()
. Please read this for more details: https://stackoverflow.com/a/53120851/143475
Upvotes: 1