Contact Us 1-800-596-4880

Flow Control in DataWeave

DataWeave 2.1 is compatible with Mule 4.1. Standard Support for Mule 4.1 ended on November 2, 2020, and this version of Mule will reach its End of Life on November 2, 2022, when Extended Support ends.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

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
%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
%dw 2.0
output application/json
var myVar = do {
    var name = "DataWeave"
    ---
    name
}
---
{ result: myVar }

Both scripts produce this output:

Output
{
  "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
%dw 2.0
output application/json
fun test(p: String) = do {
    var a = "Foo" ++ p
    ---
    a
}
---
{ result: test(" Bar") }
Output
{
  "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
%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
%dw 2.0
output application/json
---
if (payload.country =="USA")
	{ currency: "USD" }
else if (payload.country =="UK")
	{ currency: "GBP" }
else { currency: "EUR" }