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

为君一笑 提交于 2019-12-11 11:47:01

问题


I want to update a value of somewhereInJsonPath field in my JSON file.

I am using for this: * set myBody $..someWhereInJsonPath = 'AAA'. And when I run test I get: Path must not end with a '.'

But when I am using * set myBody $..firstHere.someWhereInJsonPath = 'AAA' it is working.

I think in first case, where we want to update first value in $.., it must working too.

To clarify:

For example we have JSON:

{
  "store": {
    "book": [
      {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "something": 12.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  },
  "expensive": 10
}

And when I do: $.store.book[0].something = 13 it is working.

BUT when I do: $..something = 13 it is not working.

Why? And how can I update this?

At http://jsonpath.com/ when I want to find $..something it is find this value. But when I use $..something in karate it is not working.

Realted with https://stackoverflow.com/questions/54928387/karate-jsonpath-wildcards-didnt-work-or-partly-didnt-work


回答1:


Actually the set command is not really designed for JsonPath wildcards. For example $[*].foo or $..foo are examples of wildcards. And $[0].foo, $.foo or response.foo are pure JS expressions.

So please stick to pure JS expressions like this. Here below, set is interchangeable with eval which is more useful in case you want to use dynamic / variables for e.g. * eval response[foo] where foo is a string.

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

If you really do need to do "bulk" updates, use a 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 }]


来源:https://stackoverflow.com/questions/54925553/karate-when-i-want-to-set-value-to-somewhereinjsonpath-i-get-path-must-not-e

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!