Introduction
In this post, I am going to demonstrate how to convert an array of JSON payload to a single JSON payload.Input
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | [ { "worker_id" : "AMAGWK00002673" , "position_id" : "35119973" , "requisition_id" : "R-32353" , "applicant_id" : "199505" , "staff_id" : "199504" }, { "worker_id" : "AMAGWK00002674" , "position_id" : "35119943" , "requisition_id" : "R-32353" , "applicant_id" : "199505" , "staff_id" : "199506" }, { "worker_id" : "AMAGWK00002675" , "position_id" : "35119975" , "requisition_id" : "R-32354" , "applicant_id" : "199507" , "staff_id" : "199508" } ] |
Desired Output
1 2 3 4 5 | { "AMAGWK00002673" : "199504" , "AMAGWK00002674" : "199506" , "AMAGWK00002675" : "199508" } |
Solution
The first step is to use dataweave to extrace the worker_id. This is very straight forward. The only trick about this piece of script is to use value as key in the transformed JSON result. This is achieved by using ($.key) : $.otherKey. here key = worker_id and the otherKey is staff_id.
1 2 3 | payload map ((value, index) -> { (value.worker_id): value.staff_id }) |
1 2 3 4 5 6 7 8 9 10 11 | [ { "AMAGWK00002673" : "199504" }, { "AMAGWK00002674" : "199506" }, { "AMAGWK00002675" : "199508" } ] |
In order to produce the final result, we need to use reduction reduce($$ + $).
1 2 3 | payload map ((value, index) -> { (value.worker_id): value.staff_id }) reduce($$ ++ $) |
Note: You have to use reduce ($$ ++$). The round bracket is important! The MuleSoft documentation missed that which causes many confusions.
Very informative post for mulesoft developers.You can also visit goformule.com for mulesoft stuff.
ReplyDelete