Use of do statement in Dataweave
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.
If we have to do multiple operations within a single function or variable to achieve desired result, we can use do scope.?
Examples:
1.
%dw 2.0
var myVar = 1234
var testFun =? do {
????var fName = "Adam"
????var lName = "Brown"
????---
????{
??????id : myVar,
??????firstname : fName,
??????lastname : lName
????}
}
output application/xml
---
{ person : testFun }
Result:
<?xml version='1.0' encoding='UTF-8'?>
<person>
??<id>1234</id>
??<firstname>Adam</firstname>
??<lastname>Brown</lastname>
</person>
2.
%
dw 2.0
output application/json
fun myfun() = do {
????var name = "Robert"
????---
????name
}
---
{
result: myfun()
}
Result:?
{
??"result": "Robert"
}