1

I am trying to filter response and i would like to accept multiple matches. Found that jsonPath has "in" operator to match value on the left side with array elements on the right. String concatenation is working in jsonPath query strings, but how can I add array?

 * def my_array = ["a","b"]
 * def resp = karate.jsonPath(response, "$.content[?(@.smthing in my_array)]" )

As a workaround i can use regexp instead of array. But it is just to much effort.... :(

* queryString = ""
* def func = function(x){queryString += x +"|";}
* karate.forEach(my_array,func)
* def trunc = function( ) { queryString = queryString.substring(0, queryString.length()-1) }
* trunc()
* def resp = karate.jsonPath(response, "$.content[?(@.smthing =~ /'+queryString +'/)]" )

1 Answers1

1

For complex cases like this, I recommend using karate.filter(): https://github.com/intuit/karate#json-transforms

* def myArray = ['a', 'b']
* def fun = function(x){ return myArray.includes(x) }
* def response = ['a', 'b', 'c', 'd']
* match karate.filter(response, fun) == ['a', 'b']
Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • 1
    So i try * def types = ["a","b"] * def func = function(x){return types.includes(x.type); } * def filteredByTypes = karate.filter(response.content, func ) but i get an error message : listHesMessagesForMeter.feature:25 - evaluation (js) failed: karate.filter(response.content, func ), javax.script.ScriptException: TypeError: types.includes is not a function in at line number 1 stack trace: jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470) Is it because of version 0.9.6? – MiklosBalazsi Mar 23 '21 at 17:13
  • @MiklosBalazsi yes. switch to 1.0 else use any custom JS that achieves the same thing. you can use this as a reference: https://stackoverflow.com/a/50350442/143475 – Peter Thomas Mar 23 '21 at 17:18
  • 1
    Thank you. Yes. It is working with array.prototype.indexOf() * def func = function(x){return types.indexOf(x.type) !== -1;} – MiklosBalazsi Mar 23 '21 at 17:43