我在一个多值xml标记中有一个json字符串,我很难访问它。我想将的“pid”值连接起来,使其具有如下的内容
listOfPids:"0000444,0000111“
<xml>
<custom-attributes>
<custom-attribute attribute-id="status">
<value>{
"order":"000123"
}
</value>
<value>{
"prodId": "01010101",
"status": [
{
"package": "1234",
"products": [
{
"pid": "0000444",
"amount": "2"
}
]
},
{
"package": "6789",
"products": [
{
"pid": "0000111",
"amount": "5"
}
]
}
]
}
</value>
</custom-attribute>
</custom-attributes>
</xml>我至少得到了第一个值,试着阅读和平放,但没有让它起作用.
listOfPids: read(flatten((payload.xml."custom-attributes".*"custom-attribute") filter ($.@"attribute-id" == "status"))[1].value default "", "application/json").status[0].products[0].pid发布于 2021-08-03 08:11:55
对于包含您感兴趣的json的值标记,您的输入似乎不一致。试着用下面的答案中提到的那个:
输入
<?xml version="1.0" encoding="UTF-8"?>
<custom-attributes>
<custom-attribute attribute-id="status">
<value>{
"order":"000123"
}
</value>
<value>
{
"prodId": "01010101",
"status": [{
"package": "1234",
"products": [{
"pid": "0000444",
"amount": "2"
}]
},
{
"package": "6789",
"products": [{
"pid": "0000111",
"amount": "5"
}]
}
]
}
</value>
</custom-attribute>
</custom-attributes>脚本
%dw 2.0
output json
input payload xml
---
listOfPids:(read((payload."custom-attributes"."custom-attribute")[1],"applciation/json").status..products..pid) joinBy ","输出
{
"listOfPids": "0000444,0000111"
}发布于 2021-08-04 17:39:08
这将是动态的,因为可能有更多的带有pid值的值对象,只要它们在相同的结构中,这个脚本就会将它们全部连接起来。
%dw 2.0
output application/json
var objectValues = payload.xml.'custom-attributes'.'custom-attribute'.*value
fun convertObjectsToDw(arr: Array<String>) = arr map (objectString) -> read(objectString)
---
{
listOfPids: ((convertObjectsToDw(objectValues))..status..products..pid) joinBy ", "
}发布于 2021-08-06 03:30:15
%dw 2.0
output application/json
---
listOfPids: (
payload..*value map read($, "application/json")
)..pid joinBy ","我认为这更易读,也不那么复杂。只要键值始终只有JSON字符串,您就可以选择所有字符串,然后将它们映射到结构化JSON对象中,然后选择所有pid值并加入它们。
这也有一个优点,即不管XML的深度如何,或者如果结构发生了类似于一个应答示例中的变化,它只会提取每个被调用的值并取出pids。
https://stackoverflow.com/questions/68632296
复制相似问题