Home > database >  How to provide keys with special char in karate.filterKeys?
How to provide keys with special char in karate.filterKeys?

Time:02-22

Response:

[
    {
        "key1":78,
        "key2":"value2",
        "key3": {
            "obj.key1":"objValue1",
            "obj.key2":1236527454,
        }
    },
    {
        "key1":89,
        "key2":"value2",
        "key3": {
            "obj.key1":"objValue1",
            "obj.key2":9885546755,
        }
    }
]

Expected Response:

[
    {
        "key1":32,
        "key2":"value2",
        "key3": {
            "obj.key1":"objValue1",
            "obj.key2":8985436,
        }
    },
    {
        "key1":36,
        "key2":"value2",
        "key3": {
            "obj.key1":"objValue1",
            "obj.key2":655431,
        }
    }
]

key1, obj.key2 are dynamic values that need to be ignored while comparing the rest of the JSON.

* match karate.filterKeys(response,['key1']) == karate.filterKeys(expectedResponse,['key1'])

It works as expected and ignores key1 while comparing results.

* match karate.filterKeys(response,['key1','key3["obj.key2"]') == karate.filterKeys(expectedResponse,['key1','key3["obj.key2"]']) 

The above throws error. I also tried using:

* match karate.filterKeys(response,['key1',key3['obj.key2']) == karate.filterKeys(expectedResponse,['key1',key3['obj.key2']]) 

As that's normally how special char keys are used in karate, but again getting error.

Can someone please provide a way around for this problem?

CodePudding user response:

I recommend a different approach since you have a complicated nesting and JSON that has horrible keys. Use JSON transforms to get the data in the "shape" you want, and then things become easy.

* def fun = 
"""
function(x) {
  var y = {};
  y.key2 = x.key2;
  y.key3 = {};
  y.key3['obj.key1'] = x.key3['obj.key1'];
  return y;
}
"""
* def temp = karate.map(response, fun)
* match each temp == { key2: 'value2', key3: { 'obj.key1': 'objValue1' } }
  • Related