Contact Free trial Login

Merge Multiple Payloads

This DataWeave example deals with an input that contains a collection of collections. The first payload index payload[0] lists price by book, and the second payload[1] lists authors by book, where each book can be identified by a unique bookId key. This transformation merges both payload array elements 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, payload is an array of arrays.

It uses these functions:

  • map goes through the elements of the first payload element (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
%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]
[
  { "bookId":"101",
    "title":"world history",
    "price":"19.99"
  },
  {
    "bookId":"202",
    "title":"the great outdoors",
    "price":"15.99"
  }
]
Input 2 for Collection - Payload[1]
[
  {
    "bookId":"101",
    "author":"john doe"
  },
  {
    "bookId":"202",
    "author":"jane doe"
  }
]
Output
[
  {
    "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"
  }
]

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.