MuleSoft Dataweave — Part 1

Mridul Dixit
3 min readApr 7, 2024

--

Dataweave is a programming language specifically designed by MuleSoft to access and transform data.

Mule runtime is responsible for running the script and expressions in our Mule application, DataWeave is strongly integrated with Mule runtime.

Dataweave structure :

DataWeave scripts and files are divided into two main sections:

  1. Header : The DataWeave header contains the directives, which define high level information about your transformation. The structure of the Header is a sequence of lines, each with its own Directives. The Header is terminated with ‘ — — — ’

%dw — this directive supports the specification of a previous DataWeave version on a per script basis. Use of this directive is optional. The default version is 2.0 if the directive is not present.

eg: %dw 2.0

output — Commonly used directive that specifies the mime type that the script outputs.

eg: output application/xml specifies that the output will be XML format

2. Body : The Dataweave Body contains the expression to generate the output structure. MuleSoft provides a canonical way to work on data with the DataWeave model — a query, transform, build process.

Lets play around a bit…

Click here to Try DataWeave code

Use the following Input which is in JSON format

Input

{
"fullName" : "Mridul Dixit"
}

Lets try to convert this input to different format . for eg: XML

To do this, write the following dataweave :

%dw 2.0
output application/xml
---
payload

Yayy!!! Did you see the power of Dataweave with simple example!

So now the whole JSON response is converted to XML format by just changing the output to application/xml from application/json

How to :

  1. Define a variable as an array of numbers and print :
%dw 2.0
output application/json
var arr = [1,10,22,3,25,8,12]
---
{
printArray : arr
}

2. Arrange the numbers in ascending order

ascArray : arr orderBy $

3. Arrange the array in descending order

descArray : arr orderBy -$

4. Check if the descArray contains number — 25 in it

 containsNumber : arr orderBy -$ contains 25

5. Concatenate two arrays

%dw 2.0
output application/json
var arr = [1,10,22,3,25,8,12]
var names = ["Mridul", "Ram", "Rohit"]
---
{
concatArray : arr ++ names
}

6. Remove element “Rohit” from concatenated array

 removeElement : arr ++ names -  "Rohit"

Explore more on DataWeave : MuleSoft DataWeave — Part 2

Explore more on DataWeave : MuleSoft DataWeave — Part 3

--

--

Mridul Dixit

Mulesoft Developer | Paraglider | Neuroscience Enthusiast | Curious Learner