Nav

Examples: Regrouping Fields

These 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

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
%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

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<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

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
  "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

         
      
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
---
"langs" : payload.langs groupBy $.language mapObject ((nameGroup, language) -> {
     "language" : language,
     "attendees" :
     (nameGroup map {
           name: $.name
     })
})
Input JSON

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
  "langs": [
    {
      "name": "Alex",
      "language": "Java"
    },
    {
      "name": "Kris",
      "language": "Scala"
    },
    {
      "name": "Jorge",
      "language": "Java"
    }
  ]
}
Output JSON

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
  "langs": {
    "language": "Scala",
    "attendees": [
      {
        "name": "Kris"
      }
    ],
    "language": "Java",
    "attendees": [
      {
        "name": "Alex"
      },
      {
        "name": "Jorge"
      }
    ]
  }
}