如何将参数作为键传递?

问题描述 投票:0回答:2

我有以下情况,需要使用firstKeyStr作为密钥,我的代码现在将“#firstKeyStr”视为密钥而不是存储在其中的密钥

代码

Given path '/api/v1/sites'

When method get

Then status 200
    
And match response.success == true
    
And match response.data == "#object"
    
* def keys = karate.keysOf(response.data)
    
* def firstKeyStr = keys[0]

And match response.data."#firstKeyStr" == "#object"

Json 响应正文

{

"success": true,

    "data": {

        "5ef34d0ca5a3c56ae14d2a23": {

            "devices": [

                "5f03192010a47f3e5b714193"

            ],

            "groups": [   
       
                "5f0d9f30ef89e22778a2d230"

            ],

            "users": [],

            "triggers": [],

            "alerts": [

                "5f0d92b967bac60b84d3989b"

            ],

            "name": "test",

            "country": "US",
            ]
        }
}

我正在寻找一种方法来在这一行中传递这个动态密钥(5ef34d0ca5a3c56ae14d2a23)(并匹配response.data。“#firstKeyStr”==“#object”)

karate
2个回答
1
投票

正如 Peter 所说,您的 JSON 格式不正确,并且无法保证键的顺序(除非您只有一个键)。下面的代码应该可以帮助你。

示例代码:

Feature: firstKey

Scenario: firstKey
    * def resp = 
    """
    {

    "success": true,
        "data": {
            "5ef34d0ca5a3c56ae14d2a23": {
                "devices": [
                    "5f03192010a47f3e5b714193"
                ],
                "groups": [   
           
                    "5f0d9f30ef89e22778a2d230"
                ],
                "users": [],
                "triggers": [],
                "alerts": [
                    "5f0d92b967bac60b84d3989b"
                ],
                "name": "test",
                "country": "US"
                }
            }
    }
    """
        
    And match resp.data == "#object"
    * def keys = karate.keysOf(resp.data)
    * def firstKeyStr = keys[0]
    * print firstKeyStr
    * print (resp.data[firstKeyStr])

    And match (resp.data[firstKeyStr]) == "#object"

0
投票

使用圆括号,以便使用 JS 而不是 JsonPath:

* def response = { data: { a: 1, b: 2 } }
* def keys = karate.keysOf(response.data)
* def first = keys[0]
* match (response.data[first]) == 1
© www.soinside.com 2019 - 2024. All rights reserved.