空手道:当我想将值设置为 $..somewhereInJsonPath 时,我得到 Path must not end with a '

Karate: when I want to set value to $..somewhereInJsonPath I get Path must not end with a '

我想更新 JSON 文件中 somewhereInJsonPath 字段的值。

我正在使用:* 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 它正在工作。

BUT 当我这样做时:$..something = 13 它不起作用。

为什么?我该如何更新它?

http://jsonpath.com/ 时,当我想查找 $..something 时,它就是找到这个值。但是当我在空手道中使用 $..something 时它不起作用。

实际上 set 命令并不是真正为 JsonPath 通配符设计的。例如 $[*].foo$..foo 是通配符的示例。而$[0].foo$.fooresponse.foo是纯JS表达式。

所以请坚持使用像这样的纯 JS 表达式。在下面,set 可与 eval 互换,后者在您想使用动态/变量的情况下更有用,例如* eval response[foo] 其中 foo 是一个字符串。

* def response = { foo: { somePath: 'abc' } }
* eval response.foo.somePath = 'xyz'
* match response == { foo: { somePath: 'xyz' } }

如果您确实需要进行 "bulk" 更新,请使用 transform function:

* 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 }]