Merge two json payload with dataweave

2019-09-06 10:58发布

问题:

I have a Mule flow that calls two REST API's resulting in two json list payloads. I need to obtain a merged json list from these two payloads.

I managed to achieve this with a scatter-gather flow with a custom aggregator strategy. However the code I had to write for this looks rather messy and it's slow.

Is there any way to achieve this using dataweave?`

input Json list 1:

[{ "ID": "1", "firstName": "JANE""familyName": "DOE", "Entities": [{ "ID": "515785", "name": "UNKOWN UNITED", "callSign": "UU" }] }, { "ID": "2", "firstName": "JOHN", "familyName": "DOE", "Entities": [{ "Entities_ID": "515785", "name": "UNKOWN UNITED", "callSign": "UU" }] }]

input Json list 2:

[{ "ID": "1", "firstName": "JANE", "familyName": "DOE", "Entities": [{ "Entities_ID": "8916514", "name": "UNKOWN INCORPORATED", "callSign": "UI" }] }, { "ID": "4", "firstName": "JAKE", "familyName": "DOE", "Entities": [{ "Entities_ID": "8916514", "name": "UNKOWN INCORPORATED", "callSign": "UI" }] }]

desired output is a merged list without duplicate IDs:

[{ "ID": "1", "firstName": "JANE", "familyName": "DOE", "Entities": [{ "Entities_ID": "515785", "name": "UNKOWN UNITED", "callSign": "UU" }, { "Entities_ID": "8916514", "name": "UNKOWN INCORPORATED", "callSign": "UI" }] }, { "ID": "2", "firstName": "JOHN", "familyName": "DOE", "Entities": [{ "Entities_ID": "515785", "name": "UNKOWN UNITED", "callSign": "UU" }] }, { "ID": "4", "firstName": "JAKE", "familyName": "DOE", "Entities": [{ "Entities_ID": "8916514", "name": "UNKOWN INCORPORATED", "callSign": "UI" }] }]

回答1:

This works for me with dataweave where payload is list1 and flowVars.list2 is list2

%dw 1.0
%output application/json
%var mergeddata = flowVars.list2 groupBy $.ID
---
payload map ((data,index) -> {
   ID: data.ID,
   firstName : data.firstName,
   familyName : data.familyName,
   Entities : data.Entities ++ (mergeddata[data.ID].Entities default [])
}) ++   
(flowVars.list2 filter (not (payload.ID contains $.ID)))

Hope this helps