Example of Data weave Transformations 2.0 (dw 2.0)

Reading data from XML and generate JSON

%dw 2.0
output application/json

//Get List of Countries from the XML

var Countries = payload map ((payload01 , indexOfPayload01) -> {
             Name: payload01.country
       }) distinctBy $.Name

// Get list of States from the XML

var States = payload map ((payload01 , indexOfPayload01) -> {
             Name: payload01.state,
             Country: payload01.country
       }) distinctBy $.Name     
---

Form the Payload

The below does the list of things
·       Loop through for each country
·       Loop through for each states matching the country
·       Loop through for each club matching the state
·       Order by club name and state name


{
       Countries: Countries map ((country , indexOfCountry) -> {
             Name: country.Name,
             StateProvinces: States filter ($.Country == country.Name) map ((state, indexOfState) -> {
                    Name: state.Name,
                    Clubs: payload filter ($.state == state.Name) map ((club, indexOfClub) -> {
                          ClubId: club.clubId,
                          Name: club.name,
                          City: club.city,
                          StateProvince: club.state,
                          StateProvinceAbbr: club.stateAbbr,
                          Country: club.country,
                          Level: club.membershipLevel,
                           TimeZone: club.timeZone
                    }) orderBy ($.Name)
             }) orderBy ($.Name)
       })
}


OUTPUT
{
  "Countries": [
    {
      "Name": "USA",
      "StateProvinces": [
        {
          "Name": "North Carolina",
          "Clubs": [
            {
              "ClubId": 28743,
              "Name": "Raleigh",
              "City": "Raleigh",
              "StateProvince": "North Carolina",
              "StateProvinceAbbr": "NC",
              "Country": "USA",
              "Level": "Platinum",
              "TimeZone": "America/New_York"
            }
          ]
        }
      ]
    },
    {
      "Name": "INDIA",
      "StateProvinces": [
        {
          "Name": "Tamil Nadu",
          "Clubs": [
            {
              "ClubId": 372,
              "Name": "Chennai Medavakkam",
              "City": "Chennai",
              "StateProvince": "Tamil Nadu",
              "StateProvinceAbbr": "TN",
              "Country": "INDIA",
              "Level": "Platinum",
              "TimeZone": "India/Chennai"
            }
          ]
        }
      ]
    }
  ]
}

Jayaraman Pancharathinam
20 Nov 2018

Comments

Post a Comment

Popular posts from this blog

How to read xml file and set as mock response for an http web service call in MUnit 2.1.3 in Mule 4?

How to set headers before calling a sub-flow in MUnit 2.1.3 in Mule 4?

How to mock SOAP web service call with a SOAP message in MUnit 2.1.3?