How to Update Existed Payload Value in Mule Dataweave
I Am New to Dataweave and I Want to Update Below Payload placeId Value with topValue When placeId Not Empty, I Tried Below Code but Not Working, Can Some One...
I am new to DataWeave and I want to update below payload placeId value with topValue when placeId not EMPTY , I tried below code but not working , Can some one help me please?
Code
--
%dw 2.0
output application/json
import update from dw::util::Values
var referralPayload = {"data":1,"placeId":"BSSE","topValue":1000}
---
referralPayload update(referralPayload.placeId) with if(referralPayload.placeId != null and referralPayload.placeId != "")referralPayload.topValue else referralPayload.placeId
Expected Result:
{
"data": 1,
"placeId": "1000",
"topValue": 1000
}
2 Answers
You need to pass the field name as String in the update function.
If you change your expression to referralPayload update('placeId') with then your dw will work.
To use the complicated conditional logic while updating I would recommend using the update operator rather than using dw::util::Values::update function because it provides a more clear and readable syntax
%dw 2.0
output application/json
var referralPayload = {"data":1,"placeId":"BSSE","topValue":1000}
---
referralPayload update {
case .placeId -> if(!isEmpty($)) referralPayload.topValue else $
}
Below are the two approaches based on your requirement:
- Using the "update" operator:
%dw 2.0
output application/json
var referralPayload = {"data":1,"placeId":"BSSE","topValue":1000}
---
referralPayload update {
case .placeId -> if(!isEmpty($)) referralPayload.topValue else $
}
- Using the "update" function:
%dw 2.0
output application/json
import update from dw::util::Values
var referralPayload = {"data":1,"placeId":"BSSE","topValue":1000}
---
referralPayload update "placeId" with (if(!isEmpty(referralPayload.placeId)) referralPayload.topValue else referralPayload.placeId)
Approach 1 is more optimized:
- importing a library is always a costlier process
- use of "update" operator can be used as a switch case that is more efficient in case of multiple updates operations