Suraj Ravi
Suraj Ravi

Reputation: 103

How to dynamically remove json key in Karate?

I am trying to remove some json key based on a conditon. Below didn't work

 * def body
 * if (condition == 'true') remove body.path1.path2.key
(or)
 * def body = (condition == 'true')? (remove  body.path1.path2.key):body

I am also not sure why below code is giving error

* def json = { a: 1,b:2 }
* def key = 'b'
* karate.remove('json', key)

Error: evaluation (js) failed: karate.remove('json', key), java.lang.RuntimeException: unexpected path: b

Upvotes: 1

Views: 2690

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58088

This will work:

* def json = { a: 1, b: 2 }
* def key = 'b'
* if (true) karate.remove('json', key)
* match json == { a: 1 }

So remove is a Karate keyword so it won't work when mixed with JS.

But the JS engine in 1.0 onwards will support the JS delete keyword. So you can do things like this now:

* def json = { a: 1, b: 2 }
* def key = 'b'
* if (true) delete json[key]
* match json == { a: 1 }

Upvotes: 1

Related Questions