Introduction
Here is a problem I am facing. An incoming JSON payload misses a piece of information, the transaction type. This piece of information can be deducted from the existing information. Actually, the really application is more more complicated. In this Mule Dev Trick, I am going to demonstrate how to add new information to the payload.
This small piece of code involves several key concept of Dataweave:
- map
- mapObject
- Condition statement
- Lamda sytax
Input Payload
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" : "" } ] |
The Desired Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | [ { "worker_id" : "AMAGWK00002673" , "position_id" : "35119973" , "requisition_id" : "R-32353" , "applicant_id" : "199505" , "staff_id" : "199504" , "type" : "re-hire" }, { "worker_id" : "AMAGWK00002674" , "position_id" : "35119943" , "requisition_id" : "R-32353" , "applicant_id" : "199505" , "staff_id" : "199506" , "type" : "re-hire" }, { "worker_id" : "AMAGWK00002675" , "position_id" : "35119975" , "requisition_id" : "R-32354" , "applicant_id" : "199507" , "staff_id" : "" , "type" : "new-hire" } ] |
Solution
1 2 3 4 5 6 7 8 9 | %dw 1.0 %output application/json --- payload map ((worker) ->{ (worker mapObject (value, key) -> { "$key" : value }), type : "new-hire" when worker.staff_id == null or worker.staff_id == '' otherwise 're-hire' }) |
1 2 3 4 5 6 7 8 9 | %dw 1.0 %output application/json --- payload map ((worker) ->{ (worker mapObject (value, key) -> { (key) : value }), type : "new-hire" when worker.staff_id == null or worker.staff_id == '' otherwise 're-hire' }) |
Key Learning Points
The above script seems pretty simple. It has used many key concepts of the DataWeave component. The key of the map function is to iterate a List or Array and produce a new array. And the main usage of mapObject is to iterate the attributes of an object. Both functions use Lamda expression which takes two value, $$, $. By default, $ represent the value of the current object the iterator is point to, and $$ is the index or key of the object.
Another worth noting point is that map can take single argument as well.