%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
}
})
}
}
})
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 DataWeave version 2 (%dw 2.0
) is for Mule 4 apps. For a
Mule 3 app, refer to DataWeave version 1
(%dw 1.0
) examples,
within the Mule 3.9 documentation set. For other Mule versions, you can use
the Mule Runtime version selector in the table of contents.
Both examples use these functions:
-
groupBy
to organize the fields bysubject
-
mapObject
andmap
to map the fields from the input to the new hierarchy.
Example: XML to JSON
<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>
{
"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.
%dw 2.0
output application/json
---
{
"langs" :
payload.langs groupBy $.language
mapObject ((nameGroup, language) -> {
(language): {
"attendees" : nameGroup map {
name: $.name
}
}
})
}
{
"langs": [
{
"name": "Alex",
"language": "Java"
},
{
"name": "Kris",
"language": "Scala"
},
{
"name": "Jorge",
"language": "Java"
}
]
}
{
"langs": {
"Java": {
"attendees": [
{
"name": "Alex"
},
{
"name": "Jorge"
}
]
},
"Scala": {
"attendees": [
{
"name": "Kris"
}
]
}
}
}