Contact Us 1-800-596-4880

Regroup Fields

These DataWeave examples take input that is grouped under one field and transform it into a new structure that groups data under another field. Before you begin, note that 2.x versions of DataWeave are used by Mule 4 apps. For DataWeave in Mule 3 apps, refer to DataWeave version 1.2 examples. For other DataWeave versions, you can use the version selector in the DataWeave table of contents.

Both examples use these functions:

  • groupBy to organize the fields by subject

  • mapObject and map to map the fields from the input to the new hierarchy.

Example: XML to JSON

DataWeave Script:
%dw 2.0
output application/json
---
classrooms: payload..*teacher groupBy $.subject mapObject ((teacherGroup, subject) -> {
   class: {
     name: subject,
     teachers: { (teacherGroup map {
       teacher:{
           name: $.name,
           lastName: $.lastName
       }
     })
   }
  }
})
Input XML Payload:
<school>
    <teachers>
        <teacher>
            <name>Mariano</name>
            <lastName>De Achaval</lastName>
            <subject>DW</subject>
        </teacher>
        <teacher>
            <name>Emiliano</name>
            <lastName>Lesende</lastName>
            <subject>DW</subject>
        </teacher>
        <teacher>
            <name>Leandro</name>
            <lastName>Shokida</lastName>
            <subject>Scala</subject>
        </teacher>
    </teachers>
</school>
Output JSON:
{
  "classrooms": {
    "class": {
      "name": "DW",
      "teachers": {
        "teacher": {
          "name": "Mariano",
          "lastName": "De Achaval"
        },
        "teacher": {
          "name": "Emiliano",
          "lastName": "Lesende"
        }
      }
    },
    "class": {
      "name": "Scala",
      "teachers": {
        "teacher": {
          "name": "Leandro",
          "lastName": "Shokida"
        }
      }
    }
  }
}

Example: JSON to JSON

This DataWeave example changes the hierarchy of a JSON object. The output groups fields by language and adds a new element, attendees, that contains the names of attendees for each course.

DataWeave Script:
%dw 2.0
output application/json
---
{
    "langs" :
        payload.langs groupBy $.language
            mapObject ((nameGroup, language) -> {
                 (language): {
                    "attendees" : nameGroup map {
                        name: $.name
                    }
                 }
            })
}
Input JSON Payload:
{
  "langs": [
    {
      "name": "Alex",
      "language": "Java"
    },
    {
      "name": "Kris",
      "language": "Scala"
    },
    {
      "name": "Jorge",
      "language": "Java"
    }
  ]
}
Output JSON:
{
  "langs": {
    "Java": {
      "attendees": [
        {
          "name": "Alex"
        },
        {
          "name": "Jorge"
        }
      ]
    },
    "Scala": {
      "attendees": [
        {
          "name": "Kris"
        }
      ]
    }
  }
}