Contact Free trial Login

Define DataWeave Functions

You can define your own DataWeave functions using the fun declaration in the header of a DataWeave script. Before you begin, note that DataWeave 2.0 is for Mule 4 apps. For a Mule 3 app, refer to the DataWeave 1.0 documentation set in the Mule 3.9 documentation. For other Mule versions, you can use the version selector for the Mule Runtime table of contents.

In this simple example, a DataWeave function accepts a single String argument that outputs "HELLO":

%dw 2.0
output application/json
fun toUpper(aString) = upper(aString)
---
toUpper("hello")

The argument to a DataWeave function can be any DataWeave expression. This function also outputs "HELLO":

%dw 2.0
output application/json
fun toUpper(aString) = upper(aString)
---
toUpper("h" ++ "el" ++ lower("LO") )

To test the type of the argument passed into your function, you can perform pattern matching with the built-in match operation.

Example: Function that Uses Pattern Matching
%dw 2.0
output application/json
fun toUpper(aString)
= aString match {
  case is String -> upper(aString)
  else -> null
}
---
toUpper("h" ++ "el" ++ lower("LO") )

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

Example: toPhoneFormat() Function
%dw 2.0
output application/json
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"

We use cookies to make interactions with our websites and services easy and meaningful, to better understand how they are used and to tailor advertising. You can read more and make your cookie choices here. By continuing to use this site you are giving us your consent to do this.