Nav

Flow Control in DataWeave

You can use these control flow statements within any DataWeave expression:

do

A do statement creates a scope in which new variables, functions, annotations, or namespaces can be declared and used. The syntax is similar to a mapping in that it is composed of a header and body separated by ---. Its header is where all the declarations are defined, and its body is the result of the expression.

This example uses do to return the string "DataWeave" when myfun() is called from the main body of the script.

Transform

         
      
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
fun myfun() = do {
    var name = "DataWeave"
    ---
    name
}
---
{ result: myfun() }

This example uses do to return the string "DataWeave" when the variable myVar is referenced from the main body of the script.

Transform

         
      
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
var myVar = do {
    var name = "DataWeave"
    ---
    name
}
---
{ result: myVar }

Both scripts produce this output:

Output

         
      
1
2
3
{
  "result": "DataWeave"
}

The next example uses do to prepend the string "Foo" to a string (" Bar") that is passed to the test(p: String) function.

Transform

         
      
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
fun test(p: String) = do {
    var a = "Foo" ++ p
    ---
    a
}
---
{ result: test(" Bar") }
Output

         
      
1
2
3
{
  "result": "Foo Bar"
}

if else

An if statement evaluates a conditional expression and returns the value under the if only if the conditional expression is true. Otherwise, it will return the expression under else. Every if expression must have a matching else expression.

Transform

         
      
1
2
3
4
5
6
%dw 2.0
output application/json
---
if (payload.country == "USA")
  { currency: "USD" }
else { currency: "EUR" }

else if

You can chain several else expressions together within an if-else construct by incorporating else if, for example:

Transform

         
      
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
if (payload.country =="USA")
        { currency: "USD" }
else if (payload.country =="UK")
        { currency: "GBP" }
else { currency: "EUR" }

In this topic: