空手道-如何将参数作为密钥传递?

Karate- How can I pass a param as a key?

我有以下情况,需要使用 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")

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

* def response = { data: { a: 1, b: 2 } }
* def keys = karate.keysOf(response.data)
* def first = keys[0]
* match (response.data[first]) == 1

由于您是堆栈溢出的新手,请阅读以下内容以获得最佳帮助: https://whosebug.com/help/how-to-ask https://whosebug.com/help/someone-answers

正如 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"