Data Format Manipulation in DataWeave 2.0 (Mule 4) — Using Coercing, Custom Data Types, Functions, and Flows

Author: Sanket Kangle


In addition to configuring the output structure, we also might want to format the data. One of the ways to format data is to change the data type. This is called Coercion. To coerce a property to another data type, use the “as” directive followed by the target type and optionally properties that define class or format. There are many types available in DataWeave, From the top-level type “Any” which can receive any type of data from scaler data type like number, string or boolean to more complex data types such as arrays, objects and range and even 7 types to represents dates.

Custom Data-Type

In addition to these standard data types, We can create our own custom data-types. We can define custom type data-types using the “type” header directive by providing a name and assigning the coercion properties to it. We can then use the custom data-type to coerce the data anywhere in the body. It is recommended to lead the name of custom data-type in uppercase letter and No special character is allowed. Look at the example below.


Data manipulation can also be done using DataWeave functions. Functions are packaged in modules. Functions in the core module are imported automatically into DataWeave scripts. There are two types of syntax can be used to call the function. In the following example, the function used is “contains” and two variables “payload” and “max” are used.


We can execute the flow from within a DataWeave script. It is similar to using a flow reference. It is done by using “lookup” function. The lookup function enables us to execute another flow within our application and retrieve the resulting payload. It takes two parameters, the first parameter is the flows’ name and the second parameter is an input payload that is sent to the flow as a map. This may be useful if we need to transform the payload before sending it to the flow for processing.