Nav

Example: Defining a Function that Flattens Data in a List

When presented with nested structures of data, you might need to reduce (or "flatten") the data in them to produce a simpler output. This 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:

  • map to go through a set elements in the input.

  • reduce to flatten the arrays.

  • if to conditionally display a field.

  • splitBy to parse the input.

DataWeave

         
      
1
2
3
4
5
6
7
8
9
10
11
%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)
}
Input 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
{
  "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"
}
Output JSON

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
[
  {
    "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"
  }
]

In this topic:

We use cookies to make interactions with our websites and services easy and meaningful, to better understand how they are used and to tailor advertising. You can read more and make your cookie choices here. By continuing to use this site you are giving us your consent to do this.

+