如何访问包含json字符串的多值XML



我在一个多值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>

我试图获得至少第一个值,并尝试读取和flatten,但没有得到它的工作…

listOfPids: read(flatten((payload.xml."custom-attributes".*"custom-attribute") filter ($.@"attribute-id" == "status"))[1].value default "", "application/json").status[0].products[0].pid

您的输入似乎与包含您感兴趣的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"
}

这将是动态的,因为可以有更多具有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  ", "
}
%dw 2.0
output application/json
---
listOfPids: (
payload..*value map read($, "application/json")
)..pid joinBy ","

我认为这样更容易读,也不那么复杂。只要键值始终只有JSON字符串,你可以选择所有的键值,然后将它们映射到结构化的JSON对象中,然后选择所有的pid值并将它们连接起来。

这样做还有一个优点,即无论XML文档的深度如何,或者如果结构发生了变化,例如在答案示例中,它都可以提取每个名为value的键并提取pid。

相关内容

  • 没有找到相关文章

最新更新