%dw 2.0
output application/json
fun reduceMapFor(data) = data reduce (($$ splitBy ":")[0] ++ "," ++ ($ splitBy ":")[0])
---
payload.results map() ->
{
email: $.profile.email,
name: $.profile.firstName,
tags: reduceMapFor($.data.interests.tags[0]),
(contenttypes: reduceMapFor($.data.interests.contenttypes[0])) if(sizeOf($.data.interests.contenttypes[0]) > 0)
}
Define a Function that Flattens Data in a List
|
DataWeave 2.2 is compatible and bundled with Mule 4.2. This version of Mule reached its End of Life on May 2, 2023, when Extended Support ended. 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. |
When presented with nested structures of data, you might need to reduce (or
"flatten") the data in them to produce a simpler output.
Before you begin, note that DataWeave version 2 (%dw 2.0) is for Mule 4 apps. For a
Mule 3 app, refer to DataWeave 1.0
(%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.
This DataWeave example
flattens the data in the interests and contenttypes arrays with the function
that is defined in the header, and it only outputs contenttypes when it is not
empty.
The example uses these functions:
-
mapto go through a set elements in the input. -
reduceto flatten the arrays. -
ifto conditionally display a field. -
splitByto parse the input.
{
"results": [
{
"profile": {
"firstName": "john",
"lastName": "doe",
"email": "johndoe@demo.com"
},
"data": {
"interests": [
{
"language": "English",
"tags": [
"digital-strategy:Digital Strategy",
"innovation:Innovation"
],
"contenttypes": []
}
]
}
},
{
"profile": {
"firstName": "jane",
"lastName": "doe",
"email": "janedoe@demo.com"
},
"data": {
"interests": [
{
"language": "English",
"tags": [
"tax-reform:Tax Reform",
"retail-health:Retail Health"
],
"contenttypes": [
"News",
"Analysis",
"Case studies",
"Press releases"
]
}
]
}
}
],
"objectsCount": 2,
"totalCount": 2,
"statusCode": 200,
"errorCode": 0,
"statusReason": "OK"
}
[
{
"email": "johndoe@demo.com",
"name": "john",
"tags": "digital-strategy,innovation"
},
{
"email": "janedoe@demo.com",
"name": "jane",
"tags": "tax-reform,retail-health",
"contenttypes": "News,Analysis,Case studies,Press releases"
}
]



