How to convert JSON to XML format using Dataweave?

JSON to XML transformation using Dataweave dwl scripts in Mulesoft. Use the Transform Message component in Mule flow and write your Dataweave code. A simple method for payload transformation from JSON message format to XML format using Dataweave 1.0 code.
Sample JSON code:
[
{
"Key1":0,
"Key2":"value2",
"book":[
{
"book1":5,
"book2":7
},
{
"book1":1,
"book2":0
},
{
"book1":9,
"book2":3
}
],
"mobile":[
{
"mobile1":51,
"mobile2":77,
"mobile3":66
},
{
"mobile1":10,
"mobile2":72,
"mobile3":2
},
{
"mobile1":1,
"mobile2":77,
"mobile3":5
}
]
}
]
Dataweave Code:
%dw 1.0
%output application/xml
%var payload =
[{
"Key1": 0,
"Key2": "value2",
"book": [{
"book1": 5,
"book2": 7
},
{
"book1": 1,
"book2": 0
},
{
"book1": 9,
"book2": 3
}
],
"mobile": [{
"mobile1": 51,
"mobile2": 77,
"mobile3": 66
},
{
"mobile1": 10,
"mobile2": 72,
"mobile3": 2
},
{
"mobile1": 1,
"mobile2": 77,
"mobile3": 5
}
]
}]
---
data:
{(
payload
)}
mapObject ( (value, key) ->
value match {
:array -> {( value map ( (cValue) ->
{(key) : cValue}
) )},
default -> {(key): value}
}
)
XML output:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<Key1>0</Key1>
<Key2>value2</Key2>
<book>
<book1>5</book1>
<book2>7</book2>
</book>
<book>
<book1>1</book1>
<book2>0</book2>
</book>
<book>
<book1>9</book1>
<book2>3</book2>
</book>
<mobile>
<mobile1>51</mobile1>
<mobile2>77</mobile2>
<mobile3>66</mobile3>
</mobile>
<mobile>
<mobile1>10</mobile1>
<mobile2>72</mobile2>
<mobile3>2</mobile3>
</mobile>
<mobile>
<mobile1>1</mobile1>
<mobile2>77</mobile2>
<mobile3>5</mobile3>
</mobile>
</data>
For Dataweave code syntax and other queries refer Dataweave articles. Our blog covers articles on Mule ESB integration, Connector configuration, Dataweave code, and more. Visit our blog for more interesting articles. Comment below for any queries and suggestions
0 Comments