DataWeave este limbajul de transformare integrat în Mule 4: un script are un header (%dw 2.0, output, import-uri, variabile, funcții), un separator --- și un body care descrie output-ul. Ghidul trece prin conversia tipurilor, JSON în XML și XML în JSON, citirea și scrierea CSV, operații pe array-uri și obiecte, validare cu try / orElse, module custom și setările de reader și writer care contează pentru payload-uri mari.
Petru Constantin este MuleSoft Certified Developer Level 2 (2025) și construiește API-uri MuleSoft pentru integrare enterprise din 2022. Exemplele de cod sunt scrise pe documentația Mule 4.9 LTS și DataWeave 2.9.
Concepte fundamentale DataWeave
Să înțelegem conceptele de bază ale DataWeave:
%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"
}Tipuri de date și conversii
%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
}Transformări JSON către XML
Convertește payload-uri JSON în XML cu namespace-uri:
%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
}
}
}
}Transformări XML către JSON
Gestionează XML complex cu atribute și namespace-uri:
%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
}
}
}Procesarea fișierelor CSV și flat file
Gestionează CSV cu delimitatori și headere personalizate:
%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
}
}Generare output CSV
%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"}
}Operații avansate pe array-uri
Stăpânește manipulările complexe de array-uri:
%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
})
)
}Gestionarea cheilor dinamice
Lucrează cu chei dinamice și variabile:
%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)}
)
}Gestionarea erorilor și validarea datelor
Pattern-uri de validare și conversie sigură:
%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))
}
}Funcții personalizate și module
Creează module DataWeave reutilizabile:
// 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
)Utilizarea modulelor personalizate
%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")
}Optimizarea performanței
Optimizează DataWeave pentru payload-uri mari:
%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
*/Greșeli frecvente
- Folosirea
trysauorElsefără import. Ambele sunt îndw::Runtime(de exempluimport try, orElse from dw::Runtime);orElseexistă din DataWeave 2.2.0. - Scrierea
output application/json streaming=true. Pentru JSON,streaminge o proprietate de reader; echivalentul de writer pentru output în stream estedeferred=true. - Scrierea propriei funcții
daysBetween. E funcție de core cu semnăturadaysBetween(from: Date, to: Date): Number; îi dainow() as Date, nu un DateTime. - Formatarea unui
Datecu un pattern de oră precumHH:mm:ss. Un Date nu are componentă de timp; pentru timestamp-uri folosești DateTime. - Folosirea
thenpe un runtime mai vechi. A fost introdusă în DataWeave 2.4.0.
Concluzie
Scripturile DataWeave rămân ușor de citit când fiecare face un singur lucru: convertești tipurile explicit, filtrezi înainte de map, muți logica comună în module din src/main/resources și pui conversiile riscante în try / orElse din dw::Runtime. Pentru payload-uri mari folosești proprietatea de reader streaming și proprietatea de writer deferred, iar fiecare funcție o verifici în referința DataWeave pentru versiunea inclusă în runtime-ul tău Mule.
Surse oficiale
- orElse (dw::Runtime)
- JSON Format
- daysBetween
- then
- Mule Runtime 4.9.0 Release Notes
- Precedence in DataWeave
Pe același subiect: Erori DataWeave in MuleSoft: Probleme frecvente si cum le rezolvi, Cheat Sheet functii DataWeave MuleSoft, Ghid MuleSoft Anypoint MQ: cozi, FIFO, DLQ și moduri de ACK. Mai multe articole în categoria MuleSoft, iar munca de inginerie din spatele lor e pe pagina de servicii.
Ai nevoie de un sistem AI construit și pus în producție, cu obiectivele stabilite în scris și garanția de livrare? Vezi prețul și garanția unui Sprint DeviDevs →