简体   繁体   中英

Create json array using dataweave

If I have xml like so....

<Root>
  <Authority>Water</Authority>
  <Sanctions>
    <Sanction>
      <SanctionCode>11</SanctionCode>
      <SanctionDesc>First Sanction</SanctionDesc>
    </Sanction>
    <Sanction>
      <SanctionCode>11</SanctionCode>
      <SanctionDesc>Second Sanction</SanctionDesc>
    </Sanction>          
  </Sanctions>
</Root>

Using DataWeave how can I create a json array of Santions using only the SanctionDesc?

I've tried this but it's not right...

%dw 1.0
%output application/json
---
records: payload.Root map {
   Authority: $.Authority,
   sanctions: $.Sanctions.Sanction map [$.SanctionDesc]
}

I want my output to look like this...

{
    "records": [{
        "Authority": "Water",
        "sanctions": ["First Sanction", "Second Sanction"]
    }]
}

Try this

%dw 1.0
%output application/json
---
records: {
   Authority: payload.Root.Authority,
   sanctions: payload.Root.Sanctions..SanctionDesc
}

Or

%dw 1.0
%output application/json
---
records: {
   Authority: payload.Root.Authority,
   sanctions: payload.Root.Sanctions.*Sanction map $.SanctionDesc
}

Hope this helps.

Understading the map operator is the key when picking and choosing elements from input payload. Map operator goes through all the array elements on the left hand side and we can pick the values from on right hand side, Giving example from Mulesoft portal

%dw 1.0

%output application/json

users: ["john", "peter", "matt"] map ((firstName, position) -> position ++ ":" ++ upper firstName)

Output: { "users": [ "0:JOHN", "1:PETER", "2:MATT" ] }

See link below: https://docs.mulesoft.com/mule-user-guide/v/3.8/dataweave-operators#map

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