DataWeave is the transformation language built into Mule 4: a script has a header (%dw 2.0, output, imports, variables, functions), a --- separator and a body that describes the output. This guide walks through type coercion, JSON to XML and XML to JSON, CSV reading and writing, array and object operations, validation with try / orElse, custom modules and the reader and writer settings that matter for large payloads.
Petru Constantin is a MuleSoft Certified Developer Level 2 (2025) and has built MuleSoft APIs for enterprise integration since 2022. Code examples are written against the Mule 4.9 LTS and DataWeave 2.9 documentation.
DataWeave Fundamentals
Understanding DataWeave's core concepts:
%dw 2.0
output application/json
// Header: version, output format, imports, vars and functions
---
// Body: the expression that produces the output
{
message: "Hello from DataWeave"
}Data Types and Coercion
%dw 2.0
output application/json
var inputData = {
"stringNum": "123",
"dateString": "2025-01-15",
"boolString": "true",
"nullValue": null
}
---
{
// Type coercion examples
asNumber: inputData.stringNum as Number,
asDate: inputData.dateString as Date {format: "yyyy-MM-dd"},
asBoolean: inputData.boolString as Boolean,
// Default values for null handling
withDefault: inputData.nullValue default "N/A",
// Conditional coercion
safeNumber: if (inputData.stringNum is String)
inputData.stringNum as Number
else
0
}JSON to XML Transformations
Convert JSON payloads to XML with namespaces:
%dw 2.0
output application/xml
ns soap http://schemas.xmlsoap.org/soap/envelope/
ns ord http://example.com/orders
var orderJson = {
"orderId": "ORD-12345",
"customer": {
"id": "CUST-001",
"name": "Acme Corp",
"email": "orders@acme.com"
},
"items": [
{"sku": "PROD-A", "quantity": 10, "price": 25.99},
{"sku": "PROD-B", "quantity": 5, "price": 49.99}
],
"total": 509.85
}
---
{
soap#Envelope: {
soap#Header: {},
soap#Body: {
ord#CreateOrder: {
ord#OrderHeader: {
ord#OrderId: orderJson.orderId,
ord#OrderDate: now() as String {format: "yyyy-MM-dd'T'HH:mm:ss"},
ord#Customer: {
ord#CustomerId: orderJson.customer.id,
ord#CustomerName: orderJson.customer.name,
ord#Email: orderJson.customer.email
}
},
ord#OrderLines: {
(orderJson.items map (item, index) -> {
ord#OrderLine: {
ord#LineNumber: index + 1,
ord#SKU: item.sku,
ord#Quantity: item.quantity,
ord#UnitPrice: item.price,
ord#LineTotal: item.quantity * item.price
}
})
},
ord#OrderTotal: orderJson.total
}
}
}
}XML to JSON Transformations
Handle complex XML with attributes and namespaces:
%dw 2.0
output application/json
var xmlInput = read('<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetCustomerResponse xmlns="http://example.com/customer">
<Customer id="CUST-001" status="active">
<Name>Acme Corporation</Name>
<Addresses>
<Address type="billing" primary="true">
<Street>123 Main St</Street>
<City>New York</City>
<Country>USA</Country>
</Address>
<Address type="shipping">
<Street>456 Warehouse Blvd</Street>
<City>Newark</City>
<Country>USA</Country>
</Address>
</Addresses>
<Contacts>
<Contact role="primary">John Doe</Contact>
<Contact role="billing">Jane Smith</Contact>
</Contacts>
</Customer>
</GetCustomerResponse>
</soap:Body>
</soap:Envelope>', "application/xml")
var customer = xmlInput.Envelope.Body.GetCustomerResponse.Customer
---
{
customer: {
// Access attributes with @
id: customer.@id,
status: customer.@status,
name: customer.Name,
// .* selects every repeated Address element
addresses: customer.Addresses.*Address map (addr) -> {
addressType: addr.@"type",
isPrimary: (addr.@primary default "false") == "true",
street: addr.Street,
city: addr.City,
country: addr.Country
},
contacts: customer.Contacts.*Contact map (contact) -> {
role: contact.@role,
name: contact as String
}
}
}CSV and Flat File Processing
Handle CSV with custom delimiters and headers:
%dw 2.0
output application/json
var csvData = "employee_id|first_name|last_name|department|salary|hire_date
E001|John|Doe|Engineering|85000|2020-03-15
E002|Jane|Smith|Marketing|72000|2019-08-22
E003|Bob|Johnson|Engineering|92000|2018-01-10
E004|Alice|Williams|Sales|78000|2021-05-01"
var parsedCsv = read(csvData, "application/csv", {
separator: "|",
header: true
})
---
{
totalEmployees: sizeOf(parsedCsv),
// Group by department
byDepartment: parsedCsv groupBy $.department mapObject ((employees, dept) -> {
(dept): {
count: sizeOf(employees),
totalSalary: sum(employees.salary map ($ as Number)),
avgSalary: avg(employees.salary map ($ as Number)),
employees: employees map {
id: $.employee_id,
name: $.first_name ++ " " ++ $.last_name,
salary: $.salary as Number
}
}
}),
// Find highest paid
highestPaid: (parsedCsv orderBy -(($.salary) as Number))[0] then {
name: $.first_name ++ " " ++ $.last_name,
salary: $.salary as Number,
department: $.department
}
}Generate CSV Output
%dw 2.0
output application/csv separator=",", header=true, quoteValues=true
var jsonOrders = [
{orderId: "O001", customer: "Acme", product: "Widget A", qty: 10, price: 25.99},
{orderId: "O002", customer: "Beta Inc", product: "Widget B", qty: 5, price: 49.99},
{orderId: "O003", customer: "Acme", product: "Widget C", qty: 20, price: 15.50}
]
---
jsonOrders map {
"Order ID": $.orderId,
"Customer Name": $.customer,
"Product": $.product,
"Quantity": $.qty,
"Unit Price": $.price,
"Line Total": $.qty * $.price,
"Order Date": now() as String {format: "yyyy-MM-dd"}
}Advanced Array Operations
Master complex array manipulations:
%dw 2.0
output application/json
var salesData = [
{region: "North", product: "A", q1: 100, q2: 150, q3: 120, q4: 180},
{region: "North", product: "B", q1: 80, q2: 90, q3: 110, q4: 95},
{region: "South", product: "A", q1: 200, q2: 180, q3: 220, q4: 250},
{region: "South", product: "B", q1: 150, q2: 160, q3: 140, q4: 170},
{region: "East", product: "A", q1: 90, q2: 100, q3: 95, q4: 110},
{region: "West", product: "A", q1: 120, q2: 130, q3: 125, q4: 140}
]
// Helper function for annual total
fun annualTotal(record) = record.q1 + record.q2 + record.q3 + record.q4
---
{
// Flatten quarterly data to rows
flattenedData: salesData flatMap (record) -> [
{region: record.region, product: record.product, quarter: "Q1", sales: record.q1},
{region: record.region, product: record.product, quarter: "Q2", sales: record.q2},
{region: record.region, product: record.product, quarter: "Q3", sales: record.q3},
{region: record.region, product: record.product, quarter: "Q4", sales: record.q4}
],
// Pivot: Region totals by quarter
regionQuarterPivot: salesData groupBy $.region mapObject ((records, region) -> {
(region): {
Q1: sum(records.q1),
Q2: sum(records.q2),
Q3: sum(records.q3),
Q4: sum(records.q4),
Annual: sum(records map annualTotal($))
}
}),
// Product performance ranking
productRanking: (salesData groupBy $.product mapObject ((records, product) -> {
(product): sum(records map annualTotal($))
}) pluck ((value, key) -> {product: key, totalSales: value}))
orderBy -$.totalSales,
// Find best quarter per region
bestQuarterByRegion: salesData groupBy $.region mapObject ((records, region) -> {
(region): do {
var totals = {
Q1: sum(records.q1),
Q2: sum(records.q2),
Q3: sum(records.q3),
Q4: sum(records.q4)
}
var maxVal = max(totals pluck $)
---
(totals filterObject ((v, k) -> v == maxVal) pluck $$)[0]
}
}),
// Distinct regions and products
distinctRegions: salesData.region distinctBy $,
distinctProducts: salesData.product distinctBy $,
// Cross join for all combinations
allCombinations: (salesData.region distinctBy $) flatMap ((region) ->
(salesData.product distinctBy $) map ((product) -> {
region: region,
product: product
})
)
}Dynamic Key Handling
Work with dynamic and variable keys:
%dw 2.0
output application/json
var dynamicData = {
"field_001": "value1",
"field_002": "value2",
"custom_abc": "valueA",
"custom_xyz": "valueB",
"metadata_created": "2025-01-15",
"metadata_updated": "2025-01-20"
}
var keyMapping = {
"field_001": "primaryField",
"field_002": "secondaryField"
}
---
{
// Rename keys dynamically
renamedFields: dynamicData mapObject ((value, key) -> {
((keyMapping[key as String] default key)): value
}),
// Group by key prefix
groupedByPrefix: dynamicData
pluck ((value, key) -> {key: key, value: value})
groupBy ((item) -> ((item.key as String) splitBy "_")[0])
mapObject ((items, prefix) -> {
(prefix): items reduce ((item, acc = {}) -> acc ++ {
(((item.key as String) splitBy "_")[1 to -1] joinBy "_"): item.value
})
}),
// Filter keys by pattern
customFieldsOnly: dynamicData filterObject ((v, k) ->
(k as String) startsWith "custom_"
),
// Dynamic key construction
constructedObject: ["alpha", "beta", "gamma"] reduce ((item, acc = {}) ->
acc ++ {("dynamic_" ++ item): upper(item)}
)
}Error Handling and Validation
Validation and safe conversion patterns:
%dw 2.0
output application/json
import try, orElse from dw::Runtime
var inputPayload = {
"orders": [
{"id": "O1", "amount": "100.50", "currency": "USD", "date": "2025-01-15"},
{"id": "O2", "amount": "invalid", "currency": "EUR", "date": "2025-01-16"},
{"id": "O3", "amount": "200.00", "currency": null, "date": "bad-date"},
{"id": null, "amount": "150.00", "currency": "GBP", "date": "2025-01-17"}
]
}
fun validAmount(order) = order.amount is String and (order.amount matches /^\d+(\.\d{2})?$/)
fun validDate(order) = order.date is String and (order.date matches /^\d{4}-\d{2}-\d{2}$/)
fun validateOrder(order) = do {
var errors =
(if (order.id == null) ["Missing order ID"] else []) ++
(if (!validAmount(order)) ["Invalid amount format"] else []) ++
(if (order.currency == null) ["Missing currency"] else []) ++
(if (!validDate(order)) ["Invalid date format"] else [])
---
{ isValid: isEmpty(errors), errors: errors }
}
// Safe type conversion
fun safeToNumber(val) =
if (val is String and (val matches /^-?\d+(\.\d+)?$/)) val as Number else null
fun safeToDate(val, format) =
try(() -> val as Date {format: format}) orElse null
var checked = inputPayload.orders map ((order, index) -> {
index: index,
order: order,
validation: validateOrder(order)
})
---
{
validOrders: (checked filter $.validation.isValid).order,
invalidOrders: checked filter (!$.validation.isValid) map {
orderIndex: $.index,
originalData: $.order,
errors: $.validation.errors
},
processedOrders: inputPayload.orders map ((order) -> {
id: order.id default "UNKNOWN",
amount: safeToNumber(order.amount) default 0,
currency: order.currency default "USD",
date: safeToDate(order.date, "yyyy-MM-dd"),
processed: true
}),
summary: {
total: sizeOf(checked),
valid: sizeOf(checked filter $.validation.isValid),
invalid: sizeOf(checked filter (!$.validation.isValid))
}
}Custom Functions and Modules
Create reusable DataWeave modules:
// File: src/main/resources/modules/CommonFunctions.dwl
// A module has no output directive and no body
%dw 2.0
// String utilities
fun capitalizeWord(str: String): String =
if (isEmpty(str)) str else upper(str[0]) ++ lower(str[1 to -1] default "")
fun toTitleCase(str: String): String =
(str splitBy " ") map capitalizeWord($) joinBy " "
fun truncate(str: String, maxLen: Number): String =
if (sizeOf(str) > maxLen) str[0 to maxLen - 4] ++ "..." else str
// Date utilities (for the number of days use the core function daysBetween)
fun formatDateISO(date: Date): String =
date as String {format: "yyyy-MM-dd"}
fun isBusinessDay(date: Date): Boolean = do {
var dayOfWeek = date as String {format: "E"}
---
!(dayOfWeek == "Sat" or dayOfWeek == "Sun")
}
// Currency formatting
fun formatCurrency(amount: Number, currency: String): String = do {
var symbols = {
"USD": "\$",
"EUR": "€",
"GBP": "£"
}
---
(symbols[currency] default (currency ++ " ")) ++ (amount as String {format: "#,##0.00"})
}
// Prefixed id without the dashes of the UUID
fun generateId(prefix: String): String =
prefix ++ "-" ++ ((uuid() splitBy "-") joinBy "")
// Null-safe navigation on a dotted path
fun safeGet(obj: Object, path: String): Any =
(path splitBy ".") reduce ((key, acc = obj) ->
if (acc is Object) acc[key] else null
)Using Custom Modules
%dw 2.0
output application/json
// Module file: src/main/resources/modules/CommonFunctions.dwl
import * from modules::CommonFunctions
var customerData = {
name: "john doe",
email: "JOHN.DOE@EXAMPLE.COM",
description: "This is a very long description that should be truncated for display purposes in the UI",
orderDate: "2025-01-15" as Date,
orderTotal: 1234.56
}
---
{
displayName: toTitleCase(customerData.name),
email: lower(customerData.email),
shortDescription: truncate(customerData.description, 50),
orderDateFormatted: formatDateISO(customerData.orderDate),
// daysBetween(from: Date, to: Date) is a core function
daysSinceOrder: daysBetween(customerData.orderDate, now() as Date),
totalFormatted: formatCurrency(customerData.orderTotal, "USD"),
transactionId: generateId("TXN")
}Performance Optimization
Optimize DataWeave for large payloads:
%dw 2.0
// deferred=true writes the output as a stream and defers execution until it is consumed
output application/json deferred=true
// For large inputs, streaming is a READER property, set on the input MIME type
// (for example application/json; streaming=true) and only valid when entries are read sequentially.
var largeDataset = (1 to 10000) as Array map {
id: $,
value: random() * 1000,
category: ["A", "B", "C", "D"][mod($, 4)]
}
---
{
// One pass with reduce instead of several passes
optimizedAggregation: largeDataset reduce ((item, acc = {
count: 0,
sum: 0,
categories: {}
}) -> {
count: acc.count + 1,
sum: acc.sum + item.value,
categories: acc.categories ++ {
(item.category): (acc.categories[item.category] default 0) + 1
}
}),
// Filter first, then map the smaller set
filteredFirst: largeDataset
filter ($.value > 500)
map {
id: $.id,
roundedValue: round($.value)
},
uniqueCategories: largeDataset.category distinctBy $,
preview: largeDataset[0 to 9]
}
/*
Performance tips:
1. Read large inputs with the streaming reader property when access is sequential
2. Write large outputs with deferred=true
3. Filter before mapping
4. Avoid nested loops: use groupBy and reduce
5. Keep type coercions out of tight loops
*/Common mistakes
- Using
tryororElsewithout importing them. Both live indw::Runtime(for exampleimport try, orElse from dw::Runtime);orElseexists since DataWeave 2.2.0. - Writing
output application/json streaming=true. For JSON,streamingis a reader property; the writer equivalent for streamed output isdeferred=true. - Writing your own
daysBetween. It is a core function with the signaturedaysBetween(from: Date, to: Date): Number; passnow() as Date, not a DateTime. - Formatting a
Datewith a time pattern such asHH:mm:ss. A Date has no time part; use a DateTime for timestamps. - Using
thenon an older runtime. It was introduced in DataWeave 2.4.0.
Conclusion
DataWeave scripts stay readable when each one does a single job: coerce types explicitly, filter before you map, move shared logic into modules under src/main/resources, and wrap risky conversions in try / orElse from dw::Runtime. For large payloads, use the streaming reader property and the deferred writer property, and check each function against the DataWeave reference for the version bundled with your Mule runtime.
Official references
- orElse (dw::Runtime)
- JSON Format
- daysBetween
- then
- Mule Runtime 4.9.0 Release Notes
- Precedence in DataWeave
Related on this site: MuleSoft DataWeave Errors: Common Issues and How to Fix Them, MuleSoft DataWeave Functions Cheat Sheet, MuleSoft Anypoint MQ Guide: Queues, FIFO, DLQ and ACK Modes. More articles in the MuleSoft category, and the engineering work behind them is on the services page.
Need an AI system built and running in production, with the scope agreed in writing and a delivery guarantee? See how a DeviDevs Sprint works →