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
[
{
"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
[
{
"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"
}
]
As you can see that the "type" attribute is introduced based on whether the staff_id is empty or not. If the staff_id attribute is not empty, I set the value of this attribute to "re-hire", otherwise, it will be "new-hire".
Solution
%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'
})
Note: the $key is used here. There is another syntax is (key).
Thus, the above code can be as the following:
%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.
I am sure this paragraph has touched all the internet people, its really really nice paragraph on building up new blog. Visit: I.T Consulting
ReplyDelete