You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Karate中存储动态键下ABC->XYZ对应的值?

问题:提取动态键下ABC->XYZ的值

给定如下JSON Payload,需要提取ABC->XYZ对应的值,其中外层的键"123456"是从之前API获取的动态值:

{
    "123456": {
        "Message": {
              "messageId": "abcd"
        },
        "ABC": {
            "XYZ": "REQ123456"
        }
    }
}

我尝试了以下代码片段,但输出的是动态键"123456"而非目标值"REQ123456":

* def list = []
* def fun = function(k, v){ karate.appendTo('list', { key: k, val: v } )}
* karate.forEach(response, fun)
* def keys = $list[?(@.val.ABC.XYZ)].key
* print keys

解决方法

你当前代码最后提取的是符合条件的key字段,所以得到的是动态键值。要获取XYZ的目标值,只需调整JSONPath表达式,直接提取对应属性即可:

基于现有代码修改

* def list = []
* def fun = function(k, v){ karate.appendTo('list', { key: k, val: v } )}
* karate.forEach(response, fun)
* def targetValue = $list[?(@.val.ABC.XYZ)].val.ABC.XYZ
* print targetValue

更简洁的方式(推荐)

如果已经将动态键存储在变量中(比如dynamicKey),直接通过键名访问嵌套属性,无需遍历整个响应:

* def dynamicKey = "123456" // 实际为之前API获取的动态值
* def targetValue = response[dynamicKey].ABC.XYZ
* print targetValue

内容的提问来源于stack exchange,提问作者nisha amaladhas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 16:04:55