DataWeave 2.0 provides powerful built-in functions for data transformation. This cheat sheet covers essential functions with practical examples for everyday MuleSoft development.
String Functions
Core String Operations
%dw 2.0
output application/json
var sampleText = " MuleSoft Integration Platform "
---
{
// Case transformations
upper: upper("hello"), // "HELLO"
lower: lower("HELLO"), // "hello"
capitalize: capitalize("hello world"), // "Hello World"
camelize: camelize("hello-world"), // "helloWorld"
dasherize: dasherize("helloWorld"), // "hello-world"
underscore: underscore("helloWorld"), // "hello_world"
// Trimming
trim: trim(sampleText), // "MuleSoft Integration Platform"
trimLeft: trim(sampleText) >> left(8), // "MuleSoft"
trimRight: trim(sampleText) >> right(8), // "Platform"
// Substring operations
substringBefore: substringBefore("hello@world.com", "@"), // "hello"
substringAfter: substringAfter("hello@world.com", "@"), // "world.com"
substringBeforeLast: substringBeforeLast("a.b.c", "."), // "a.b"
substringAfterLast: substringAfterLast("a.b.c", "."), // "c"
// Size and padding
sizeOf: sizeOf("hello"), // 5
leftPad: leftPad("42", 5, "0"), // "00042"
rightPad: rightPad("42", 5, "0"), // "42000"
// Search operations
contains: contains("hello world", "world"), // true
startsWith: startsWith("hello", "he"), // true
endsWith: endsWith("hello", "lo"), // true
indexOf: "hello" find "l", // [2, 3]
// Replace operations
replace: replace("hello", "l", "L"), // "heLLo"
replaceRegex: "abc123" replace /\d+/ with "XXX" // "abcXXX"
}Advanced String Functions
%dw 2.0
output application/json
import * from dw::core::Strings
---
{
// Split and join
splitBy: "a,b,c" splitBy ",", // ["a", "b", "c"]
joinBy: ["a", "b", "c"] joinBy "-", // "a-b-c"
// Character operations
charCode: charCode("A"), // 65
charCodeAt: charCodeAt("ABC", 1), // 66
fromCharCode: fromCharCode(65), // "A"
// Pluralization
pluralize: pluralize("box"), // "boxes"
singularize: singularize("boxes"), // "box"
// Ordinalize
ordinalize: ordinalize(1), // "1st"
ordinalizeSecond: ordinalize(2), // "2nd"
ordinalizeThird: ordinalize(3), // "3rd"
// Word operations
words: words("hello world test"), // ["hello", "world", "test"]
lines: lines("line1\nline2\nline3"), // ["line1", "line2", "line3"]
// Check functions
isAlpha: isAlpha("hello"), // true
isAlphanumeric: isAlphanumeric("hello123"), // true
isNumeric: isNumeric("12345"), // true
isWhitespace: isWhitespace(" "), // true
isEmpty: isEmpty(""), // true
isBlank: isBlank(" "), // true
// Repeat and reverse
repeat: repeat("ab", 3), // "ababab"
reverse: reverse("hello") // "olleh"
}Array Functions
Core Array Operations
%dw 2.0
output application/json
var numbers = [1, 2, 3, 4, 5]
var users = [
{name: "Alice", age: 30},
{name: "Bob", age: 25},
{name: "Charlie", age: 35}
]
---
{
// Transformation
map: numbers map ($ * 2), // [2, 4, 6, 8, 10]
mapWithIndex: numbers map (item, idx) -> {
index: idx,
value: item
},
// Filtering
filter: numbers filter ($ > 2), // [3, 4, 5]
filterObject: users filter ($.age >= 30), // Alice and Charlie
// Reduction
reduce: numbers reduce (a, b) -> a + b, // 15
reduceRight: [1, 2, 3] reduce (a, b) -> a - b, // -4
// Finding
find: users filter ($.name == "Bob"), // [{name: "Bob", age: 25}]
contains: numbers contains 3, // true
// Flattening
flatten: [[1, 2], [3, 4], [5]] flatten, // [1, 2, 3, 4, 5]
flatMap: [[1, 2], [3, 4]] flatMap ($ map ($ * 2)), // [2, 4, 6, 8]
// Sorting
orderBy: users orderBy $.age, // Sorted by age ascending
orderByDesc: users orderBy -$.age, // Sorted by age descending
// Grouping
groupBy: users groupBy $.age > 28, // Grouped by condition
// Distinct
distinctBy: [1, 2, 2, 3, 3, 3] distinctBy $, // [1, 2, 3]
// Size operations
sizeOf: sizeOf(numbers), // 5
isEmpty: isEmpty([]), // true
// Partition
partition: numbers partition ($ > 3), // {success: [4,5], failure: [1,2,3]}
}Array Manipulation Functions
%dw 2.0
output application/json
import * from dw::core::Arrays
var items = [1, 2, 3, 4, 5]
---
{
// Access elements
first: items[0], // 1
last: items[-1], // 5
head: items[0], // 1
tail: items[1 to -1], // [2, 3, 4, 5]
// Slice operations
slice: items[1 to 3], // [2, 3, 4]
take: items take 3, // [1, 2, 3]
drop: items drop 2, // [3, 4, 5]
takeWhile: items takeWhile ($ < 4), // [1, 2, 3]
dropWhile: items dropWhile ($ < 4), // [4, 5]
// Combination
concat: items ++ [6, 7], // [1, 2, 3, 4, 5, 6, 7]
prepend: 0 >> items, // [0, 1, 2, 3, 4, 5]
append: items << 6, // [1, 2, 3, 4, 5, 6]
// Set operations
union: [1, 2, 3] ++ [3, 4, 5] distinctBy $, // [1, 2, 3, 4, 5]
intersection: ([1, 2, 3] filter ([3, 4, 5] contains $)), // [3]
difference: [1, 2, 3] filter (not ([3, 4, 5] contains $)), // [1, 2]
// Chunking
divideBy: items divideBy 2, // [[1, 2], [3, 4], [5]]
// Zip operations
zip: [[1, 2], ["a", "b"]] reduce (a, b) ->
(a zip b) map ($ joinBy ":"), // ["1:a", "2:b"]
// Sum and statistics
sum: sum(items), // 15
avg: avg(items), // 3
min: min(items), // 1
max: max(items), // 5
// Index operations
indexOf: items indexOf 3, // 2
lastIndexOf: [1, 2, 3, 2, 1] lastIndexOf 2, // 3
// Boolean checks
every: items every ($ > 0), // true
some: items some ($ > 4), // true
none: items every ($ < 0) // false (using every with negation)
}Object Functions
Core Object Operations
%dw 2.0
output application/json
var user = {
firstName: "John",
lastName: "Doe",
email: "john@example.com",
age: 30
}
---
{
// Key-value operations
keys: keysOf(user), // ["firstName", "lastName", "email", "age"]
values: valuesOf(user), // ["John", "Doe", "john@example.com", 30]
entries: entriesOf(user), // [{key: "firstName", value: "John"}, ...]
// Transformation
mapObject: user mapObject {
(upper($$)): $
}, // {FIRSTNAME: "John", ...}
// Filtering
filterObject: user filterObject ($ is String), // Remove age
// Pluck (extract values with transformation)
pluck: user pluck {
field: $$,
val: $
},
// Merge objects
merged: user ++ {country: "USA", age: 31}, // Overwrites age
// Remove keys
withoutAge: user - "age", // Object without age
withoutMultiple: user -- ["age", "email"], // Remove multiple keys
// Rename keys
renamed: user mapObject ((v, k) ->
if (k ~= "firstName") {first_name: v}
else if (k ~= "lastName") {last_name: v}
else {(k): v}
),
// Default values
withDefault: user.middleName default "N/A", // "N/A"
// Null safety
safeAccess: user.address?.city default "Unknown",
// Check existence
hasKey: user.firstName?, // true
keyPresent: user["firstName"]? // true
}Dynamic Object Construction
%dw 2.0
output application/json
var fieldMappings = [
{source: "fn", target: "firstName"},
{source: "ln", target: "lastName"},
{source: "em", target: "email"}
]
var sourceData = {
fn: "Jane",
ln: "Smith",
em: "jane@example.com"
}
---
{
// Dynamic key construction
dynamicKeys: {
("user_" ++ "name"): "John",
("user_" ++ "id"): 123
},
// Conditional keys
conditionalObject: {
name: "Test",
(if (true) {active: true} else {}),
(if (false) {hidden: true} else {})
},
// From entries
fromMappings: fieldMappings reduce ((mapping, acc = {}) ->
acc ++ {(mapping.target): sourceData[mapping.source]}
),
// Recursive object transformation
deepTransform: do {
fun transform(obj) = obj match {
case o is Object -> o mapObject ((v, k) ->
{(lower(k as String)): transform(v)}
)
case a is Array -> a map transform($)
else -> obj
}
---
transform({FirstName: "John", Address: {City: "NYC", ZIP: "10001"}})
}
}Date and Time Functions
Date Operations
%dw 2.0
output application/json
import * from dw::core::Periods
var today = now()
---
{
// Current date/time
now: now(),
todayDate: now() as Date,
currentTime: now() as Time,
// Parsing dates
parseDate: "2025-01-15" as Date,
parseDateTime: "2025-01-15T10:30:00Z" as DateTime,
parseCustom: "15/01/2025" as Date {format: "dd/MM/yyyy"},
// Formatting
formatDate: today as String {format: "yyyy-MM-dd"},
formatDateTime: today as String {format: "yyyy-MM-dd'T'HH:mm:ss"},
formatCustom: today as String {format: "MMMM dd, yyyy"},
formatLocale: today as String {format: "EEEE, MMMM d, yyyy", locale: "en-US"},
// Extract components
year: today.year,
month: today.month,
day: today.day,
hour: today.hour,
minute: today.minutes,
second: today.seconds,
dayOfWeek: today.dayOfWeek,
dayOfYear: today.dayOfYear,
// Date arithmetic
addDays: today + |P7D|, // Add 7 days
subtractDays: today - |P7D|, // Subtract 7 days
addMonths: today + |P1M|, // Add 1 month
addYears: today + |P1Y|, // Add 1 year
addHours: today + |PT2H|, // Add 2 hours
addMinutes: today + |PT30M|, // Add 30 minutes
// Comparison
isBefore: |2025-01-01| < |2025-12-31|, // true
isAfter: |2025-12-31| > |2025-01-01|, // true
isEqual: |2025-01-01| == |2025-01-01|, // true
// Period between dates
daysBetween: |2025-01-01| - |2025-01-15|, // Period
// Timezone operations
withTimezone: today >> "America/New_York" as TimeZone,
utc: today >> |+00:00|,
// Start/End of periods
startOfDay: today as Date ++ |T00:00:00|,
endOfDay: today as Date ++ |T23:59:59|
}Period and Duration Functions
%dw 2.0
output application/json
import * from dw::core::Periods
---
{
// Period definitions
oneDay: |P1D|,
oneWeek: |P7D|,
oneMonth: |P1M|,
oneYear: |P1Y|,
complex: |P1Y2M3D|,
// Duration (time-based)
oneHour: |PT1H|,
thirtyMinutes: |PT30M|,
tenSeconds: |PT10S|,
combined: |PT1H30M|,
// Period arithmetic
doublePeriod: |P7D| * 2, // 14 days
halfPeriod: |P10D| / 2, // 5 days
// Calculate age
birthDate: |1990-05-15|,
age: do {
var birth = |1990-05-15|
var today = now() as Date
---
years(between(birth, today))
},
// Business days calculation
businessDays: do {
fun addBusinessDays(startDate, days) = do {
var result = startDate + |P1D|
var dayOfWeek = result.dayOfWeek
---
if (days <= 0) startDate
else if (dayOfWeek == 6 or dayOfWeek == 7)
addBusinessDays(result, days)
else
addBusinessDays(result, days - 1)
}
---
addBusinessDays(|2025-01-06|, 5) // Skip weekends
}
}Type Coercion Functions
Type Conversions
%dw 2.0
output application/json
---
{
// String conversions
numberToString: 123 as String, // "123"
boolToString: true as String, // "true"
dateToString: |2025-01-15| as String, // "2025-01-15"
// Number conversions
stringToNumber: "123" as Number, // 123
stringToFloat: "123.45" as Number, // 123.45
boolToNumber: true as Number, // 1
// Boolean conversions
stringToBool: "true" as Boolean, // true
numberToBool: 1 as Boolean, // true
zeroBool: 0 as Boolean, // false
// Date conversions
stringToDate: "2025-01-15" as Date,
stringToDateTime: "2025-01-15T10:30:00Z" as DateTime,
epochToDateTime: 1704067200000 as DateTime {unit: "milliseconds"},
// Binary conversions
stringToBase64: "Hello" as Binary,
base64ToString: "SGVsbG8=" as String {encoding: "UTF-8"},
// Type checking
isString: "hello" is String, // true
isNumber: 123 is Number, // true
isArray: [1,2,3] is Array, // true
isObject: {a: 1} is Object, // true
isNull: null is Null, // true
// Safe coercion with default
safeNumber: ("abc" as Number default 0), // 0
safeDate: ("invalid" as Date default |2025-01-01|),
// Typeof
typeOfString: typeOf("hello"), // "String"
typeOfNumber: typeOf(123), // "Number"
typeOfArray: typeOf([1,2,3]), // "Array"
typeOfObject: typeOf({a: 1}) // "Object"
}Utility Functions
Common Utilities
%dw 2.0
output application/json
import * from dw::core::Numbers
import * from dw::Runtime
---
{
// Null handling
nullDefault: null default "fallback", // "fallback"
isBlankCheck: isBlank(""), // true
// Conditional expressions
ifElse: if (true) "yes" else "no",
unless: unless (false) "executed",
// Match expressions
matchType: "hello" match {
case s is String -> "It's a string: " ++ s
case n is Number -> "It's a number"
else -> "Unknown type"
},
// Pattern matching
matchPattern: "user@example.com" match {
case email if (email contains "@") -> "Valid email format"
else -> "Invalid"
},
// UUID generation
uuid: uuid(),
// Random numbers
randomInt: randomInt(100), // 0-99
random: random() * 100, // 0.0-99.9
// Number operations
round: round(3.7), // 4
floor: floor(3.7), // 3
ceil: ceil(3.2), // 4
abs: abs(-5), // 5
sqrt: sqrt(16), // 4
pow: pow(2, 3), // 8
mod: mod(10, 3), // 1
// Logging (outputs to console)
logged: log("Debug message", {key: "value"}),
// Error handling
tryCatch: try(() -> "123" as Number) default -1,
// Recursive functions
factorial: do {
fun fact(n) = if (n <= 1) 1 else n * fact(n - 1)
---
fact(5) // 120
},
// Memoization pattern
fibonacci: do {
var cache = {}
fun fib(n) =
if (n <= 1) n
else fib(n - 1) + fib(n - 2)
---
fib(10) // 55
}
}Binary and Encoding Functions
%dw 2.0
output application/json
import * from dw::core::Binaries
var originalText = "Hello MuleSoft!"
---
{
// Base64 encoding/decoding
toBase64: toBase64(originalText as Binary),
fromBase64: fromBase64("SGVsbG8gTXVsZVNvZnQh") as String,
// Hex encoding
toHex: toHex("ABC" as Binary),
// URL encoding
urlEncode: encodeURI("hello world & special=chars"),
urlDecode: decodeURI("hello%20world%20%26%20special%3Dchars"),
// Hash functions
md5: do {
import dw::Crypto
---
Crypto::hashWith("Hello" as Binary, "MD5")
},
sha256: do {
import dw::Crypto
---
Crypto::hashWith("Hello" as Binary, "SHA-256")
},
// HMAC
hmacSha256: do {
import dw::Crypto
---
Crypto::HMACWith("message" as Binary, "secret" as Binary, "HmacSHA256")
}
}XML-Specific Functions
XML Operations
%dw 2.0
output application/xml
var xmlData = read('<root xmlns:ns="http://example.com">
<ns:item id="1">Value 1</ns:item>
<ns:item id="2">Value 2</ns:item>
</root>', "application/xml")
---
{
// Namespace handling
withNamespace: {
ns0#root @(xmlns#ns0: "http://example.com"): {
ns0#element: "value"
}
},
// CDATA sections
withCDATA: {
root: {
script: "<![CDATA[function() { return true; }]]>" as CData
}
},
// Attributes
withAttributes: {
element @(id: "123", class: "main"): "content"
},
// Processing instructions
withPI: {
"?xml-stylesheet": {
"@type": "text/xsl",
"@href": "style.xsl"
}
},
// Comments
withComment: {
root: {
"!--": "This is a comment",
element: "value"
}
}
}Quick Reference Table
| Category | Function | Example | Result |
|----------|----------|---------|--------|
| String | upper | upper("abc") | "ABC" |
| String | lower | lower("ABC") | "abc" |
| String | trim | trim(" abc ") | "abc" |
| String | replace | "abc" replace "b" with "B" | "aBc" |
| Array | map | [1,2] map $ * 2 | [2,4] |
| Array | filter | [1,2,3] filter $ > 1 | [2,3] |
| Array | reduce | [1,2,3] reduce $$ + $ | 6 |
| Array | flatten | [[1],[2]] flatten | [1,2] |
| Object | mapObject | {a:1} mapObject {(upper $$): $} | {A:1} |
| Object | keysOf | keysOf({a:1}) | ["a"] |
| Date | now | now() | Current DateTime |
| Date | as Date | "2025-01-15" as Date | Date object |
| Type | as String | 123 as String | "123" |
| Type | as Number | "123" as Number | 123 |
| Utility | uuid | uuid() | UUID string |
| Utility | default | null default "x" | "x" |
Conclusion
This cheat sheet covers essential DataWeave 2.0 functions for MuleSoft development. Bookmark this reference for quick lookup during transformation development. Practice combining these functions to build complex data transformations efficiently.