Contact Us 1-800-596-4880

Regroup Fields

DataWeave 2.1 is compatible with Mule 4.1. Standard Support for Mule 4.1 ended on November 2, 2020, and this version of Mule will reach its End of Life on November 2, 2022, when Extended Support ends.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

These DataWeave examples take input that is grouped under one field and transform it into a new structure that groups data under another field.

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
%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
<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": "Scala",
      "teachers": {
        "teacher": {
          "name": "Leandro",
          "lastName": "Shokida"
        }
      }
    },
    "class": {
      "name": "DW",
      "teachers": {
        "teacher": {
          "name": "Mariano",
          "lastName": "De Achaval"
        },
        "teacher": {
          "name": "Emiliano",
          "lastName": "Lesende"
        }
      }
    }
  }
}

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:
Unresolved include directive in modules/ROOT/pages/dataweave-cookbook-regroup-fields.adoc - include::2.3@partial$cookbook-dw/regroup-fields-ex2/transform.dwl[]
Input JSON Payload:
Unresolved include directive in modules/ROOT/pages/dataweave-cookbook-regroup-fields.adoc - include::2.3@partial$cookbook-dw/regroup-fields-ex2/inputs/payload.json[]
Output JSON:
Unresolved include directive in modules/ROOT/pages/dataweave-cookbook-regroup-fields.adoc - include::2.3@partial$cookbook-dw/regroup-fields-ex2/out.json[]