简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM