If you’re familiar with popular languages like Java, or C#, you’ll notice the way DataWeave implements if/else is much closer to a ternary expression that the if/else statements you see in those languages. The difference is very simple, however. DW uses if/else expressions that returns values, Java and C# us if/else statements that do not return values.
If/else expressions can be chained together, meaning you can do multiple checks before you return any data. Here’s the format for how that works:
if (<criteria_expression1>) <return_if_true> else if (<criteria_expression2>) <return_if_true> else <return_if_no_other_match>
You can have as many of these if/else chains as necessary.
You can chain several else expressions together within an if-else construct by incorporating else if. The following example uses the input var myVar = { country : "UK" }, which is defined by the myVar variable in the header. DataWeave Script:
%dw 2.0
var myVar = { country : "UK" }
output application/json
---
if (myVar.country =="USA")
{ currency: "USD" }
else if (myVar.country =="UK")
{ currency: "GBP" }
else { currency: "EUR" }
Output
{
"currency": "GBP"
}
The following example is similar but takes an array as input instead of an object. The body of the script uses if else and else if statements within a do operation to populate the value of the hello variable. DataWeave Script:
%dw 2.0
output application/json
---
["Argentina", "USA", "Brazil"] map (country) -> do {
var hello = if(country == "Argentina") "Hola"
else if(country == "USA") "Hello"
else if(country == "Brazil") "Ola"
else "Sorry! We don't know $(country)'s language."
---
"$(hello) DataWeave"
}
Output:
[ "Hola DataWeave", "Hello DataWeave", "Ola DataWeave" ]
Follow Me If you like my post please follow me to read my latest post on programming and technology. Instagram Facebook

Leave a Comment
You must be logged in to post a comment.