空手道:从API响应中查找特定元素值的索引

时间:2019-05-17 11:31:28

标签: karate

我用于查找索引的代码如下

* def list = nestActual #this is API response value which is given at the end
* def searchFor = { category_name: 'books3'}
* def foundAt = []
* def fun = function(x, i){ if (karate.match(x, searchFor).pass) foundAt.add(i) }
* eval karate.forEach(list, fun)
* print "==========foundAt=======" +foundAt

我已经尝试了上面的代码来查找索引,而我在foundAt索引中获得的值为null。

下面是我想在其中找到“ category_name”的索引:“ books3”的

[
{
"category_id":1, "parent_cat_id":0, "category_name":"books", "slug_name":"books_1", "popular":true,

}, {
"category_id":2, "parent_cat_id":1, "category_name":"books2", "slug_name":"books_2", "popular":false,

}, {
"category_id":3, "parent_cat_id":1, "category_name":"books3", "slug_name":"books3_2", "popular":false,

}, {
"category_id":4, "parent_cat_id":3, "category_name":"mp3", "slug_name":"mp_3", "popular":false, }, {
"category_id":5, "parent_cat_id":3, "category_name":"mp4", "slug_name":"humoristiska_deckare_mysi_deck_3", "popular":false, }, {
"category_id":6, "parent_cat_id":3, "category_name":"video", "slug_name":"video3", "popular":false,

} ]

请让我知道如何使用空手道找到“ category_name”:“ books3”的索引

1 个答案:

答案 0 :(得分:1)

猜猜有什么简单的方法,诀窍是将搜索目标转换为原始数组。然后,您可以使用List.indexOf() Java方法:

Scenario: using the java indexOf api (will change with graal)
    * def response = [{ name: 'a' }, { name: 'b' }, { name: 'c' }]
    * def names = $[*].name
    * def index = names.indexOf('b')
    * match index == 1