Is it possible to get XML nodes always as array even if there is only one?

我们两清 提交于 2020-01-25 04:35:26

问题


I'm testing a SOAP webservice using Karate. One of the methods is that depending on the request, the response can return one or more coincidences. When transforming that XML response to JSON, if there is only one result, it's is interpreted as an object, but if there are more, then it's an array.

Is there any way to make that for a given path, it is always returned as an array?

Example XML with only one match:

<matches>
    <product>...</product>
</matches

Resulting JSON structure:

{ 
    matches: {
        product: ...,
    }
}

Example XML with more than one match:

<matches>
    <product>...</product>
    <product>...</product>
    <product>...</product>
</matches

Resulting JSON structure:

{ 
    matches: [
        { product: ... },
        { product: ... },
        { product: ... },
    ]
}

Looking at the documentation from get, it says:

A convenience that the get syntax supports (but not the $ short-cut form) is to return a single element if the right-hand-side evaluates to a list-like result (e.g. a JSON array). This is useful because the moment you use a wildcard [*] or search filter in JsonPath (see the next section), you get an array back - even though typically you would only be interested in the first item.

But I've been trying and did not get it to work. I don't know if that is the way to do it or there is a better/working one.


回答1:


Unfortunately, no - this is indeed a difference in the way XML and JSON work in Karate. So you will have to do some custom logic. For e.g:

* def temp = { foo: { bar: { a: 1 } } }
# * def temp = { foo: [{ bar: { a: 1 } }] }
* if (temp.foo.bar) karate.set('temp', '$.foo', [temp.foo])
* match temp == { foo: [{ bar: { a: 1 } }] }

So just 1 line can "normalize" the JSON if you are sure it always has to be an array.



来源:https://stackoverflow.com/questions/58541610/is-it-possible-to-get-xml-nodes-always-as-array-even-if-there-is-only-one

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