Merge two json payload with dataweave

喜你入骨 提交于 2019-12-25 08:06:32

问题


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



来源:https://stackoverflow.com/questions/39723094/merge-two-json-payload-with-dataweave

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!