I have a JSON array that looks something like this -
{ “products”: [ { “code”: “abc”, “name”: “test” }, { “code”: “abc2”, “name”: “test2” }, … ] }
I’d like to loop over the json array and check the length using Karate. f the number of keys in each item. Using the example above, the length of the number of keys should be 2. Any help would be greatly appreciated!
I’ve tried just getting the keys by doing
However, it just returns null and doing karate.sizeOf returns the total size instead of the size of each item.
Personally I think you should be doing better assertions, like checking the keys and values. Refer this answer.
But anyway, this is how your question can be answered:
* def products = [{a: 1, b: 2}, {x: 1, y: 2}]
* def sizes = products.map(x => Object.keys(x).length)
* match each sizes == 2
For an explanation of map()
refer: https://stackoverflow.com/a/76091034/143475
And Object.keys()
is a standard JS function, similar to karate.keysOf()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys