karate - 空手道:当我想将值设置为 $..somewhereInJsonPath 我得到路径不能以'结尾
问题描述
我想更新somewhereInJsonPath
我的 JSON 文件中的字段值。
我正在使用这个:* set myBody $..someWhereInJsonPath = 'AAA'
。当我运行测试时,我得到:Path must not end with a '.'
但是当我使用* set myBody $..firstHere.someWhereInJsonPath = 'AAA'
它时它正在工作。
我认为在第一种情况下,我们想要更新 $.. 中的第一个值,它也必须工作。
澄清:
例如我们有 JSON:
{
"store": {
"book": [
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"something": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
当我这样做时: $.store.book[0].something = 13 它正在工作。
但是当我这样做时: $..something = 13 它不起作用。
为什么?我该如何更新呢?
在http://jsonpath.com/当我想找到 $..something 它是找到这个值。但是当我在空手道中使用 $..something 时,它不起作用。
解决方案
实际上,该set
命令并不是真正为 JsonPath 通配符设计的。例如$[*].foo
or$..foo
是通配符的例子。And $[0].foo
, $.foo
orresponse.foo
是纯 JS 表达式。
所以请坚持使用这样的纯 JS 表达式。在下面,如果您想使用动态 / 变量,例如where is a string ,set
可与eval
哪个更有用。* eval response[foo]
foo
* def response = { foo: { somePath: 'abc' } }
* eval response.foo.somePath = 'xyz'
* match response == { foo: { somePath: 'xyz' } }
如果您确实需要进行“批量”更新,请使用转换功能:
* def response = [{}, {}]
* def fun = function(x, i){ return { foo: 'bar', index: ~~(i + 1) } }
* def res = karate.map(response, fun)
* match res == [{ foo: 'bar', index: 1 }, { foo: 'bar', index: 2 }]