Nav

About DataWeave Functions

You define a function using the fun declaration in the header section. Like other programming languages, DataWeave functions allow you to refactor DataWeave expressions into reusable code blocks. In DataWeave, every code block is an expression that is immediately evaluated when it is called from the DataWeave body expression. Functions can define and use one or more arguments.

Here is a simple DataWeave function that accepts a single String argument:


         
      
1
2
3
4
5
%dw 2.0
output application/json
fun toUpper(aString) = upper(aString)
---
toUpper("hello") //results in "HELLO"

The argument to a DataWeave function can be any DataWeave expression. This function produces the same result as the previous example:


         
      
1
2
3
4
5
%dw 2.0
output application/json
fun toUpper(aString) = upper(aString)
---
toUpper("h" ++ "el" ++ lower("LO") ) //results in "HELLO"

Because any DataWeave expression can be passed into a function, you might need to test the type of argument passed into a function before using the expression. The match operator can be helpful for this:


         
      
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
fun toUpper(aString)
= aString match {
  case is String -> upper(aString)
  else -> null
}
---
toUpper("h" ++ "el" ++ lower("LO") ) //results in "HELLO"

This example creates a function that reformats a numeric string into a common phone number format:

Example: toPhoneFormat() Function

         
      
1
2
3
4
fun toPhoneFormat(str: String) =
    "(" ++ str[0 to 2] ++ ") " ++ str[3 to 5] ++ "-" ++ str[6 to 9]
---
toPhoneFormat("1234567890")
Output of toPhoneFormat("1234567890")
"(123) 456-7890"

In this topic: