GettingStarted With123
GettingStarted With123

Reputation: 427

Dataweave : Transform XML to JSON

Using Mule 4.4 community edition and am using Dataweave to perform transformation. Payload is in XML as below :

    <Result>    
        <TRNO>abcd</TRNO>   
    <EMPS>
        <EMP>
        <NAME>JOHN</NAME>
        <AGE>21</AGE>               
        </EMP>
        <EMP>
        <NAME>TOM</NAME>
        <AGE>18</AGE>               
        </EMP>
    </EMPS>
</Result>

I need JSON as below:

    {
  "trackId": "abcd",
  "empDetails": [
    {
      "empName": "JOHN",
      "empAge": "21"
    },
    {
      "empName": "TOM",
      "empAge": "18"
    }
  ]
}

I am trying to generate using following dataweave but its erroring out :

    %dw 2.0
output application/json writeAttributes=true
---
if (payload.Result.EMPS.EMP?)
    "trackId": payload.Result.TRNO,   
    empDetails:payload.Result.EMPS.*EMP map {        
        empName: $.NAME,
        empAge: $.AGE        
    } 

else
null

It does not like this line "trackId": payload.Result.TRNO, before the array population. The error is :

Invalid input ',', expected FieldName (line 5, column 35):

5| "trackId": payload.Result.TRNO,
^ Location: main (line: 5, column:35)

Upvotes: 0

Views: 275

Answers (1)

StackOverflowed
StackOverflowed

Reputation: 759

Just give braces enclosing your if , should be good.

%dw 2.0
output application/json  writeAttributes=true
---
if (payload.Result.EMPS.EMP?)
  {
    "trackId": payload.Result.TRNO,
    empDetails: payload.Result.EMPS.*EMP map {
      empName: $.NAME,
      empAge: $.AGE
    }
  }
else
  null

Upvotes: 1

Related Questions