Search code examples
automationkarate

How to iterate through a nested array of objects in karate and also to sort it?


 Here goes my code:
{
"infolist": [
{
"id": 1,
"marketList":[
{"datevalue": "2020-03-01",
"year": "2020"
},
{
"datevalue": "2021-03-01",
"year": "2021"
}
]
},
{
"id": 2,
"marketList":[
{"datevalue": "2018-03-01",
"year": "2018"
},
{
"datevalue": "2020-03-01",
"year": "2020"
}
]
}
]
}
  1. I want to sort this entire object which my response based on every datevalue field which is present in each marketList array of every object of the infoList array.

I understand that this json object is very nested. But is there any way I can achieve this via karate?


Solution

  • I'm focusing only on the array under infoList as a variable called response:

    * def dates = $response[*].marketList[*]
    * def sorted = karate.sort(dates, x => x.datevalue)
    

    I'm assuming you just want all the dates since your question is not clear at all. For more hints refer this part of the docs: https://github.com/karatelabs/karate#json-transforms

    For karate.sort() refer to the documentation: https://github.com/karatelabs/karate#karate-sort

    Here is an example to explain how it works. That x is a JS function argument. Take the help of someone who knows JS functions if needed:

    * def foo = [{a: { b: 3 }}, {a: { b: 1 }}, {a: { b: 2 }}]
    * def fun = function(x){ return x.a.b }
    * def bar = karate.sort(foo, fun)
    * match bar == [{a: { b: 1 }}, {a: { b: 2 }}, {a: { b: 3 }}]