user3355101
user3355101

Reputation: 231

How to remove an object from an jsonarray based on filter in karate

I want to remove an object from json array based on a filter, tried below code but didn't work

* def json = [ { "id": "0a7936ed", "code": "test", "label": "test", "type": "sell" }, { "id": "7bc1909b2", "code": "test2", "label": "test2", "type": "Buy" } ]

I want remove object where code is equal to test

* def fun = function(){ karate.remove('json', $.[?(@.code=='test')]") }
* call fun

Getting exception as below:

com.intuit.karate.exception.KarateException: javascript function call failed: String index out of range: -1
    at com.intuit.karate.Script.evalFunctionCall(Script.java:1622)
    at com.intuit.karate.Script.call(Script.java:1573)
    at com.intuit.karate.Script.callAndUpdateConfigAndAlsoVarsIfMapReturned(Script.java:1690)
    at com.intuit.karate.StepDefs.callAndUpdateConfigAndVars(StepDefs.java:582)

Please suggest me how to filter it and remove the object. Thanks inadvance..

Upvotes: 2

Views: 6361

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58088

This use-case is exactly what karate.filter() is designed for:

* def json = [ { "id": "0a7936ed", "code": "test", "label": "test", "type": "sell" }, { "id": "7bc1909b2", "code": "test2", "label": "test2", "type": "Buy" } ]
* def condition = function(x){ return x.code != 'test' }
* def filtered = karate.filter(json, condition)
* match filtered == [{ "id": "7bc1909b2", "code": "test2", "label": "test2", "type": "Buy" }]

Here is the documentation: https://github.com/intuit/karate#the-karate-object

Upvotes: 9

Related Questions