Nav

Working with Functions and Lambdas in DataWeave

In DataWeave, function and lambdas (anonymous functions) can be passed as values or be assigned to variables.

When using lambdas within the body of a DataWeave file in conjunction with an function such as map, its attributes can either be explicitly named or left anonymous, in which case they can be referenced as $, $$, etc.

To Declare and Invoke a Function

You can declare a function in the header or body of a DataWeave script by using the fun keyword. Then you can invoke the function at any point in the body of the script.

You refer to functions using this form: functionName() or functionName(arg1, arg2, argN)

You can pass an expression in between the parentheses for each argument. Each expression between the parentheses is evaluated, and the result is passed as an argument used in the execution of the function body.

Input

         
      
1
2
3
4
5
{
  "field1": "Annie",
  "field2": "Point",
  "field3": "Stuff"
}
Transform

         
      
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
fun toUser(obj) = {
  firstName: obj.field1,
  lastName: obj.field2
}
---
{
  "user" : toUser(payload)
}
Output

         
      
1
2
3
4
5
6
{
  "user": {
    "firstName": "Annie",
    "lastName": "Point"
  }
}

To Assign a Lambda to a Var

You can define a function as a variable with a constant directive through var

Input

         
      
1
2
3
4
5
{
  "field1": "Annie",
  "field2": "Point",
  "field3": "Stuff"
}
Transform

         
      
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
var toUser = (user) -> {
  firstName: user.field1,
  lastName: user.field2
}
---
{
  "user" : toUser(payload)
}
Output

         
      
1
2
3
4
5
6
{
  "user": {
    "firstName": "Annie",
    "lastName": "Point"
  }
}

To Use Named Parameters in a Lambda

This example uses a lambda with an attribute that is explicitly named as name.

Input

         
      
1
2
3
4
5
%dw 2.0
output application/json
var names = ["john", "peter", "matt"]
---
users: names map((name) -> upper(name))
Transform

         
      
1
2
3
{
  "users": ["JOHN","PETER","MATT"]
}

To Use Anonymous Parameters in a Lambda

This example uses a lambda with an attribute that’s not explicitly named, and so is referred to by default as $.

Transform

         
      
1
2
3
4
5
%dw 2.0
output application/json
var names = ["john", "peter", "matt"]
---
users: names map upper($)
Output

         
      
1
2
3
{
  "users": ["JOHN","PETER","MATT"]
}