1
votes

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"]
    }]
}
2

2 Answers

3
votes

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.

0
votes

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