Karate-查找JSON响应数组中元素多次出现的数组索引

问题描述 投票:1回答:1

我有一个来自端点的JSON响应,该响应给了我一个嵌套的元素数组。在给定输入值的情况下,我想找出出现此值的所有索引值,而不仅仅是元素的第一次出现。

例如,这是我的答复:

{
    "items": [
        {
            "vin": "MMTestingVIN00002",
            "dealerCode": "1",
            "nmscCode": "1",
            "warning": {
                "warningLightType": {
                    "code": 1,
                    "description": "",
                    "symbol": "OLW",
                    "type": "S",
                    "priority": "1"
                }
            }
        },
        {
            "vin": "HESQM0IBWUR7DH0DU",
            "dealerCode": "1",
            "nmscCode": "1",
            "warning": {
                "warningLightType": {
                    "code": 1,
                    "description": "",
                    "symbol": "OLW",
                    "type": "S",
                    "priority": "1"
                }
            }
        },
        {
            "vin": "MMTestingVIN00002",
            "dealerCode": "1",
            "nmscCode": "1",
            "warning": {
                "warningLightType": {
                    "code": 1,
                    "description": "",
                    "symbol": "OLW",
                    "type": "S",
                    "priority": "1"
                }
            }
        },
        {
            "vin": "ZCADWKEQM1GEADEQR",
            "dealerCode": "1",
            "nmscCode": "1",
            "warning": {
                "warningLightType": {
                    "code": 1,
                    "description": "",
                    "symbol": "WASH",
                    "type": "S",
                    "priority": "1"
                }
            }
        },
        {
            "vin": "H5QGE06R54B8KYOUV",
            "dealerCode": "1",
            "nmscCode": "1",
            "warning": {
                "warningLightType": {
                    "code": 1,
                    "description": "",
                    "symbol": "WASH",
                    "type": "S",
                    "priority": "1"
                }
            }
        }
    ]
}

我想找出带有"vin = MMTestingVIN00002"的数组所在的索引。

我在https://github.com/intuit/karate/blob/master/karate-junit4/src/test/java/com/intuit/karate/junit4/demos/js-arrays.feature中寻找想法。还查看了其他SO答案并尝试过:

* def VIN = 'MMTestingVIN00002'
* def response = result.items
* def names = $[*].vin
* def index = names.indexOf(VIN)
* print index

这仅给出索引0的第一个出现。理想情况下,我想要一个结果数组index [],其结果为[0,2]。

karate
1个回答
0
投票

您在这里:

* def indexes = []
* def fun = function(x, i){ if (x.vin == 'MMTestingVIN00002') karate.appendTo(indexes, i) }
* karate.forEach(response.items, fun)
© www.soinside.com 2019 - 2024. All rights reserved.