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
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…