Suraj Ravi
Suraj Ravi

Reputation: 103

How to compare two json objects using Karate where order of element is to be retained?

I am in a need to compare 2 JSON objects where the order has retained while comparing. As Karate match ignores the order of an element, I am just curious to know if there is a way to do so in Karate.

Upvotes: 2

Views: 939

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58153

Not directly, it is never needed, since JSON keys can be in any order, like a Map.

But you can do an exact match after converting to a (normalized) string:

* def foo = { a: 1, b: 2 }
* string str1 = foo
* string str2 = { "a": 1, "b": 2 }
* assert str1 == str2

You can also get an ordered list of keys / values at any time:

* def vals = karate.valuesOf(foo)
* match vals == [1, 2]
* def keys = karate.keysOf(foo)
* match keys == ['a', 'b']

Upvotes: 1

Related Questions