【问题标题】:Cannot read attribute from JSON element无法从 JSON 元素读取属性
【发布时间】:2026-01-21 20:00:01
【问题描述】:

我正在尝试从负载中的属性中获取值,但空手道抛出错误或根本没有获取值。

我创建了我的代码的简化版本,使其更易于理解。

* def lists = [{@id: 1, type: 'video'}, {@id: 2, type: 'image'}]
* def ser = {@id: 2, type: '#string'}

* def foundAt = []
* def fun = function(x, i){ if (karate.match(x, ser).pass) foundAt.add(i) }
* eval karate.forEach(lists, fun)
* def storeId = lists[foundAt[0]].@id
* def storeType = lists[foundAt[0]].type
* print storeId
* print storeType

print storeType 将按预期打印值,但 print storeId 将打印以下错误消息:

javascript evaluation failed: lists[foundAt[0]].@id, <eval>:1:18 Expected ident but found error
lists[foundAt[0]].@id
                  ^ in <eval> at line number 1 at column nu*mber 18

我希望打印值“2”,但显然我做错了什么?

【问题讨论】:

    标签: automated-tests karate


    【解决方案1】:

    一个小改动就可以解决问题,因为@ 是 JSON 键名的“坏”字符:

    * def storeId = lists[foundAt[0]]['@id']
    

    这也是对您的代码的建议简化:

    * def fun = function(x, i){ return karate.match(x, ser).pass }
    * def found = karate.filter(lists, fun)
    * def storeId = found[0]['@id']
    * def storeType = found[0].type
    * print storeId
    * print storeType
    

    【讨论】:

      最近更新 更多