0
votes

I am trying to transform a JSON object to an XML object using Mule Dataweave. Below is the input JSON:

{
    "root": {
        "OBJECT1": {
            "PARAM1": "PARAM1VALUE",
            "PARAM2": "PARAM2VALUE"
        },
        "OBJECT2": [{
            "KEY": "PARAMROWKEYVALUE1",
            "VALUE": "PARAMROWVALUEVAL1"
        }, {
            "KEY": "PARAMROWKEYVALUE2",
            "VALUE": "PARAMROWVALUEVAL2"
        }],
        "OBJECT3": {
            "PARAM3": "PARAM3VALUE",
            "PARAM4": "PARAM4VALUE"
        }
    }
}

I want to transform the above to the XML below:

<root>
    <node1>PARAM1VALUE PARAM2VALUE</node1>
    <args>
        <paramrow>
            <KEY>PARAMROWKEYVALUE1</KEY>
            <VALUE>PARAMROWVALUEVAL1</VALUE>
        </paramrow>
        <paramrow>
            <KEY>PARAMROWKEYVALUE2</KEY>
            <VALUE>PARAMROWVALUEVAL2</VALUE>
        </paramrow>
    </args>
    <details>
        <PARAM3>PARAM3VALUE</PARAM3>
    </details>
</root>

But, when I used this JSON as sample input, it throws an error saying "validate mapping":

%dw 1.0
%output application/xml
---
payload

How do I map these object elements to XML?

3

3 Answers

1
votes

Try the following DataWeave

%dw 1.0
%output application/xml
---
{
    root: {
        node1: payload.root.OBJECT1.PARAM1 ++ ' ' ++ payload.root.OBJECT1.PARAM2,
        args: {
            (payload.root.OBJECT2 map {
                paramrow: {
                    KEY: $.KEY,
                    VALUE: $.VALUE
                }
            })
        },
        details: {
            (payload.root.OBJECT3 mapObject {
                '$$': $
            })
        }
    }
}
0
votes

Consider using the official MuleSoft Developer docs.

A lot of DataWeave examples and the complete reference can be found there.

https://docs.mulesoft.com/mule-user-guide/v/3.7/dataweave-examples#json-to-xml https://docs.mulesoft.com/mule-user-guide/v/3.7/dataweave-reference-documentation

0
votes

@mlucas67, yes the dataweave expression works.

Here is another way which i have tried.

%dw 1.0
%input payload application/json
%output application/xml
---
{
    root: {(payload map {
        node1: $.OBJECT1.PARAM1 ++ ' ' ++ $.OBJECT1.PARAM2,
        args: {
            ($.OBJECT2 map paramrow: $)
        },
        details: 
            PARAM3: $.OBJECT3.PARAM3
    })
    }
}

Thank you all commented on this post.