Nav

Example: Merge Multiple Payloads

This example deals with an input that contains a collection of payloads. The first payload lists price by book, the second lists authors by book, where each book can be identified by a unique bookId key. This transformation merges both payloads into one, matching their keys, where one book may have several authors.

Note that this is not the same as having as an input a single payload that consists of an array. Here, there are multiple separate payload elements within one single Mule Event object. This kind of data structure can be produced, for example, by a scatter-gather component.

It uses these functions:

  • map goes through the elements of the first payload (payload[0]). While on each element, a second map function goes through the elements of the second payload (payload[1]) that match the filter criteria.

  • using defines a shorter alias within the scope of the main map function.

  • filter limits the scope of the second map function to only objects that share the same bookId as is currently being processed by the first map function. In that way, only relevant authors for each are listed in the output.

DataWeave

         
      
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
output application/json
---

payload[0]  map (bookListing) -> using (id = bookListing.bookId) {
        bookId:        id,
    title:  bookListing.title,
        price:         bookListing.price as Number,
        (payload[1] filter ($.*bookId contains id)  map (bookAuthor) -> {
                author:bookAuthor.author
   })
}
Input 1 for Collection - Payload[0]

         
      
1
2
3
4
5
6
7
8
9
10
11
[
  { "bookId":"101",
    "title":"world history",
    "price":"19.99"
  },
  {
    "bookId":"202",
    "title":"the great outdoors",
    "price":"15.99"
  }
]
Input 2 for Collection - Payload[1]

         
      
1
2
3
4
5
6
7
8
9
10
[
  {
    "bookId":"101",
    "author":"john doe"
  },
  {
    "bookId":"202",
    "author":"jane doe"
  }
]
Output

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[
  {
    "bookId": "101",
    "title": "world history",
    "year": "2017",
    "isbn": "11111",
    "price": "19.99",
    "author": "john doe"
  },
  {
    "bookId": "202",
    "title": "the great outdoors",
    "year": "2016",
    "isbn": "22222",
    "price": "15.99",
    "author": "jane doe"
  }
]

In this topic: