Bonjour!

Just like any other programming language, In Mule4, dataweave provides match function to achieve the functionality of if-else statements. 

A match expression contains a list of case statements that can optionally have an else statement. Each case statement consists of a conditional selector expression that must evaluate to either true or false.

Let’s consider a scenario where you need to update certain fields of incoming payload keeping the rest of the fields as it is, you can use a match and case

for example, the following is the input JSON object:

Input:

{
    “address”: {
     “houseNumber” : null,
“street” : “IOC Road”,
“pincode” : “111222”,
“landmark” : “Statue of unity”,
“city” : “Ahmedabad”,
“state” : “Gujarat”,
“country” : “India”
    }
}

Dataweave Transformation:

%dw 2.0
output application/json
var flag = if (payload.address.houseNumber == null) false else true
{
“updateAddressRequest”:
payload.address mapObject (value,key,index) ->(
key as String match {
case “pincode” -> {(key): “000000”}
case “houseNumber” -> {(key): if(flag == false) “00” else “”}
else -> {(key):(value)}
}
)
}


Output:


{
“updateAddressRequest”: {
“houseNumber”: “00”,
“street”: “IOC Road”,
“pincode”: “000000”,
“landmark”: “Statue of unity”,
“city”: “Ahmedabad”,
“state”: “Gujarat”,
“country”: “India”
}
}

What we did here with the input JSON object is that we matched the keys using keyword match and then based on a condition updated the value of the key. We then used the else keyword in order to keep the rest of the fields the same as the input. 

In above example we are updating houseNumer and pincode field with case and other fields are remains same with else block.

This is also an example of how we can use the match case with mapObject

Pattern matching using Match Case can be done on Literal values, on expressions, on Data Types, and on Regular Expressions. 

Adios amigos!


Leave a Reply

Your email address will not be published. Required fields are marked *