I have an input payload which is coming as xml. I'm looking for a json output in the format of object as shared below. Input Payload:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<item>
<item_status>2</item_status>
<item_number>null</item_number>
<details>
<order_flag>
<tag>0000</tag>
<item_line>
<item_quantity>10</item_quantity>
<count>1</count>
</item_line>
<item_line>
<item_quantity>8</item_quantity>
<count>5</count>
</item_line>
</order_flag>
<order_flag>
<tag>1111</tag>
<item_line>
<item_quantity>15</item_quantity>
<count>2</count>
</item_line>
<item_line>
<item_quantity>25</item_quantity>
<count>3</count>
</item_line>
</order_flag>
</details>
</item>
desired Output:
{
"item_status": "2",
"item_number": null,
"order_flag": {
"tag": "0000",
"item_line": [
{
"item_quantity":"10",
"count":"1",
"brand": "null"
},
{
"item_quantity":"8",
"count":"5"
"brand": "null"
}
]
},
"order_flag":{
"tag":"1111",
"item_line":[
{
"item_quantity":"15",
"count":"2"
"brand": "null"
},
{
"item_quantity":"25",
"count":"3",
"brand": "null"
}
]
}
}
In the incoming payload there is order flag which coming as an array of objects and inside the tag there item line which array of objects too. but the required output should be as above. Thanks for your input
The method I used is to get all the contents of the order_flag elements in an array, using the multi-valued selector, then map to the desired format per element, then use reduce() to convert the array into an object concatenating the items of the array into an object.
%dw 2.0
output application/json
---
{
item_status: payload.item.item_status,
item_number: payload.item.item_number,
((payload.item.details.*order_flag map
{
order_flag: {
tag: $.tag,
item_line: ($.*item_line map ($ ++ {brand: null}))
}
}
) reduce ((item, acc={})->acc ++ item))
}
Output:
{
"item_status": "2",
"item_number": "null",
"order_flag": {
"tag": "0000",
"item_line": [
{
"item_quantity": "10",
"count": "1",
"brand": null
},
{
"item_quantity": "8",
"count": "5",
"brand": null
}
]
},
"order_flag": {
"tag": "1111",
"item_line": [
{
"item_quantity": "15",
"count": "2",
"brand": null
},
{
"item_quantity": "25",
"count": "3",
"brand": null
}
]
}
}