How to append default email id domain to incoming payload in Dataweave transformation (DW 2.0)

50 Views Asked by At

Need help with Dataweave transformation (DW 2.0)

I have an incoming payload which looks like below: I want to divide input list in the batch of 3 and add a default email id to the customer id's coming in the input payload so that it can be passed to the next flow which will iterate these objects and send them to end system for processing.

Input Payload

{
    "application": "salesforce",
    "payload": {
            "activeCustomersReturned": 9,
            "activeCustomers": [
                "c4444",
                "c2345",
                "c9099",
                "c1234",
                "c3456",
                "c0876",
                "c4589",
                "c4139",
                "c9189"
            ]
        }
}

desired output is:

[
  {
    "CustomerData": [
      "[email protected]",
      "[email protected]",
      "[email protected]"
    ]
  },
  {
    "CustomerData": [
      "[email protected]",
      "[email protected]",
      "[email protected]"
    ]
  },
  {
    "CustomerData": [
      "[email protected]",
      "[email protected]",
      "[email protected]"
    ]
  }
]

I tried the below DW Script, it is able to break the input into list of 3 objects, however I am unable to append the email id using ++ operator as the item is an array

%dw 2.0
import * from dw::core::Arrays
output application/json

var activeCustomers = payload.payload.activeCustomers divideBy 3
---

(activeCustomers) map ((item, index) -> {
     "CustomerData": item
})

//Not working code
// (activeCustomers) map ((item, index) -> {
//     "CustomerData": item as String ++ "@gmail.com" 
// })
2

There are 2 best solutions below

0
Scott On

You're very close. The divideBy function creates nested arrays, so you just need map the item(s) and wrap the append in ( ) like:

%dw 2.0
import * from dw::core::Arrays
output application/json

var activeCustomers = payload.payload.activeCustomers divideBy 3
---

(activeCustomers) map ((item, index) -> {
     "CustomerData": item map ($ ++ "@gmail.com")
})
1
Harshank Bansal On

An alternate solution can be to do the map first and then divideBy 3 to avoid the confusion and handling the nested array.

%dw 2.0
import divideBy from dw::core::Arrays
output application/json
---
payload.payload.activeCustomers 
    map "[email protected]"
    divideBy 3
    map {CustomerData: $}