0% found this document useful (0 votes)
2K views4 pages

Dataweave 2.0 Cheat Sheet

This document provides a cheat sheet for DataWeave 2.0, MuleSoft's data transformation language. It includes examples of functions, lambdas, conditionals, string interpolation, and data types like objects, arrays, dates and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views4 pages

Dataweave 2.0 Cheat Sheet

This document provides a cheat sheet for DataWeave 2.0, MuleSoft's data transformation language. It includes examples of functions, lambdas, conditionals, string interpolation, and data types like objects, arrays, dates and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

DATAWEAVE 2.

0
CHEAT SHEET

DataWeave is the MuleSoft expression language for accessing and transforming data
that travels through a Mule app, which runs the scripts and expressions in your Mule app

DEFINE FORMATTING
function(param) fun toUser(obj) = { firstName: obj.fname } Currency type Currency = String { format: “##“}

function(function param) fun combined(function, msg="universe") = function(msg {"combined": "HELLO WORLD"} Date formattedDate: |2003-10-01T23:57:59|
++ " world") --- combined: combined(toUpper, "hello") as String {format: "yyyy-MM-dd"}

function fun test(p: String) = do { var a = "Foo" ++ p --- a } { "result": "Foo Bar"}
---
{ result: test(" Bar") }

ESCAPE CHAR
lambda var msg2 = (x = "ignore") -> "hello" --- msg2: msg2() {"msg2": "hello"} {"b": "dollar sign (\$)"}
\

Note: For escaping $$, use \$\$

lambda (param) var toUpper = (aString) -> upper(aString) {"toUpper": "HELLO"}


--- toUpper: toUpper("hello")

REGEX
lambda (function param) var combined = (function, msg="universe") -> { "combined": "HELLO WORLD" } One or more digits from 0-9
/\d+/
function(msg ++ " WORLD")
-- combined: combined(toUpper, "hello")

NAMESPACE ns ns0 http://www.pk.com ns0#book : "works" One or more chars


/\s+/

Case Statement value match { "hello world" match { [


["+1 (415) 123-7890"] map ($ match {
case (<name>:) <condition> -> <routing expression> case word matches /(hello)\s+\w+/ -> {
case phone matches
case (<name>:) <condition> -> <routing expression> word[1] as String ++ " was matched" "country": "1",
else -> <when none of them matched> case literalMatch: "hello world" -> /\+(\d+)\s\((\d+)\)\s(\d+\-\d+)/ -> { "area": "415",
} upper(literalMatch) country: phone[1], area: phone[2], "number": "123-7890"
case hasOne if( hasOne is Object and
number: phone[3]}}) }
hasOne.three? ) -> hasOne.three
]
else -> $ /* case last if(true) -> last
*/
}

Global Variable var myVar ="Hello"

STRING INTERPOLATION
Local variable var myAge = do { var age = "25" --- age } { "Name": "John Doe", "Age": "25"} var name ="pk" --- {"details": "pk and age 25"}
--- { Name : do { var name = "John Doe" --- name }, Age :
{ details: ""$name and age ${24 +
myAge}
1}"}
Comments // or /* */

DYNAMIC ELEMENTS
Object Collection of name:value pairs { name: "John Doe" } {"a": "a","e": "e"}
var y = {e: "e"} --- { a: "a", (y)}

[1,2]
Array

CONDITIONAL ASSIGNMENT
if (expression) "True value" if (isOdd(3)) "value is odd"
else "value is even"
else "False Value"

IF ELSE DATE
If Else if (condition1) {} if (payload.country =="USA") Date |2003-10-01|
{ currency: "USD" }
else if (condition2) {}
else if (payload.country =="UK")
else {} { currency: "GBP" }
else { currency: "EUR" }

DateTime |2003-10-01T23:57:59-03:00|

LocalDateTime |2003-10-01T23:57:59|

JAVA
header (import function ) imports class utils.MyUtils from LocalTime A Time in the current TimeZone
import java!utils::MyUtils::someFunction
src/main/java

header (import function import valueOf from java!java::lang::String Period P<date>T<time> - P[n]Y[n]M[n]DT[n]H[n]M[n]S

directly)

body (creating a new java!java::lang::NullPointerException::new("foo") Time |23:59:56|

instance)

TimeZone |-09:00|

DYNAMIC KEY
{"MyKey": " It works!"} Date Decomposition <DATE>.year
var dynamicKey = "MyKey"
<DATE>.month
---
(dynamicKey): " It works!"

Test the selectors using the following input

<users xmlns="www.pk.corp"><user name="pk">John Doe</user><user name="vik">Vikram</user></users>

SELECTORS (Static) SELECTORS(Dynamic)


Single Value payload.users.user "John Doe" Single Value payload[("users")] { "user": "John Doe", "user": "Vikram"}

Multi-value payload.users.*user [ "John Doe", "Vikram"] Multi-value payload[*("users")] [{ "user": "John Doe", "user": "Vikram"}]

Descendants payload..users.user ["John Doe"] Atributes payload.users.*user[@"name"] ["pk","vik"]

Key&Value payload.users.&user { "user": "John Doe", Key&Value payload.users[&("user")] { "user": "John Doe", "user": "Vikram"}
"user": "Vikram"}

Index payload.users[0] "John Doe" Single Value payload.ns0#"users" { "user": "John Doe", "user": "Vikram"}

with NS where ns ns0 www.pk.corp

Range payload.users.*user[0 to 1] [ "John Doe", "Vikram"]

XML Attribute payload.users.user.@name "pk"

NameSpace payload.users.# www.pk.corp


SELECTORS CONDITIONAL
Element (hello: "world") if (true) { "hello": "world"}

Key Present payload.user? "false" Array [(1) if true, (2) if false] [1]

Attribute Present payload.users.user.@name? "true" XML Attribute {name @((age: "25") if true): "John <name age="25">John Doe</name>

conditional Doe"}

Asset Present payload.user! Error - "There is no key XML Attributes transform @((payload.users)): "That <transform
named 'user'" Dynamic changed everything" xmlns:wstxns1=”www.pk.corp”
wstxns1:user="John Doe"
wstxns1:user="Vikram">That changed
everything</transform>

Filter (Array or payload.users.*user[?($=="Vikram")] ["Vikram"]

null)

Dataweave Library and Functions HOW TO


pluralize pluralize("bar") bars Rename Keys inside mapObject use,
(newkey: value) if(key as String ==
'oldkey')

upper upper("bar") BAR Output conditionally inside map use,


(insurance: $.insurance)
if($.insurance?)

lower lower("BAR") bar Default values (SomeField default "DefaultValue") (payload.someField default
"my default value")

camelize camelize("BAR") bAR Conditional Assignment if (expression) "True value" if (isOdd(3)) "value is odd"
else "False Value" else "value is even"

capitalize capitalize("bar") Bar zip (use INPUT2) payload map (item, index) -> [{"screws":[[4,15],[6,8]]}]
{ screws: zip(item.screws.size,
item.screws.quantity)}

p (read property) Mule::p('http:port') 8081 Exclude Fields ( - ) personal_information:


$.personal_information - "ssn"

lookup (execute Mule::lookup('flow2', {test:'hello '}) reduce [{"channels":["ABN","Gemini","ETV", [{ "channels": "ABN,Gemini,ETV

flow) "NDTV"]}] ,NDTV" }]


map() ->{(channels:
reduceMapFor($.channels))
if(sizeOf($.channels) > 0)}

causedBy Mule::causedBy('HTTP:FORBIDDEN') Read XML read(XML) var myInput = read('<bookstore>


<book>…

flatten flatten([[3],[null],null]) [3,null,null] Insert Attributes in "@(<attributeName> : <value>)" title @(lang: "en", year: "2001"):

XML element "Da Vinci Code"

filter [9,2,3,4,5] filter (value, index) -> (value > 2) [9,3,4,5] Merge Fields from [ { "bookId":"101", "title":"world [{ "theTitle": "world history",

different objects history" }] map (firstInputValue) -> "theAuthor": "john doe" }]


{ theTitle: firstInputValue.title, ([ {
"bookId":"101", "author":"john doe"}]
filter ($.*bookId contains
firstInputValue.bookId) map
(secondInputValue) ->
theAuthor : secondInputValue.author
)}

filterObject {"a" : "apple", "b" : "banana"} filterObject { "a": "apple" } DWL expression from <when
((value) -> value == "apple") file expression="${file::someFile.dwl}" >

find ["Bond", "James", "Bond"] find "Bond" [0,2] Load DWL as Module import modules::MyModule MyModule.dwl resides in
import myFunc as myFunction, myVar /src/main/resources/modules
as myVarValue from
modules::MyModule
groupBy ["a","b","c"] groupBy (item, index) -> {"2":["c"],"1":["b"],"0":["a"] }
index
Dataweave Library and Functions
isBlank "empty" : isBlank("") "empty": true uuid uuid() "cafaae62-3b57-4879-a2aa-
cadefa6c652f"

isEmpty [ isEmpty([]), isEmpty([1]) ] [ true, false ] splitBy "192.168.1.1/24" splitBy(/[.\/]/) ["192", "168", "1", "1", "24"]

map payload.users.*user map ((item,index) -> [{"user":"John replace with { "ssn" : "987-65-4321" replace /[0-9]/ { "ssn": "xxx-xx-xxxx" }
{user : item}) Doe"},{"user":"Vikram"}] with("x") }

mapObject payload mapObject (value, key) -> (key): {"users":{"user":"John write write(payload.users, "user|user\nJohn Doe|Vikram\n"
value Doe","user":"Vikram"}} "application/csv",
{"header":true, "separator" : "|"})

match "[email protected]" match(/([a-z]*)@([a- ["[email protected]", "me", to (Range) { "customRange": 1 to 5 } { "customRange": [1, 2, 3, 4, 5] }


z]*).com/) "mulesoft"]

orderBy [{ letter: "e" }, { letter: "d" }] [{"letter":"d"},{"letter":"e"}] envVar envVar("SHELL") "/bin/bash"


orderBy($.letter)

matches ("john Doe123" matches /j.*\d+/) "true" read { person : { "person": {"name": "john"}}
read('<name>john</name>','applicatio
n/xml') }

pluck {"name":"john","age":"25"} pluck [{"column":{"0":{"john":"name"}}},{"c contains { "1or2There?" : if(contains("12345", {"1or2There?":"yes"


(value,key,index) -> field: { (index) : { olumn":{"1":{"25":"age"}}}] /[1-2]/)) "yes" else "no" ,"RamThere?":true }
(value):key} } ,"cotainsRam?" :
contains("Vikram","ram")}

concat (++) { "concat" : ["A", "B"] ++ ["C", "D"]} {"concat":["A","B","C","D"] }

Timezone
remove (--) { "remove": ["A", "B"] -- ["A"] {"remove":["B"] } Add/Subtract a period {anYearTwoMonthsAnd3DaysAgo: {
} (Year/Month/Days/Time) (now() - |P1Y2M3D|) as LocalDateTime "anYearTwoMonthsAnd3DaysAgo":
{format : "dd-MM-yyyy'T'HH:mm:ss"}} "29-01-2019T04:04:57"
(P[n]Y[n]M[n]DT[n]H[n
}
]M[n]S)

Math Operations { "Answer" : 2 * (2 / 2) +2 - 2 } { "Answer": 2.0} Append Timezone { "DateTime" : (|2019-10-01T23:57:59| { "DateTime": "2019-10-01T23:57:59-03:00 }

(+,-,/,*) ++ |-03:00|) }

Relational ( >, >=, var x=8 var strTrue="true" { Shift Timezone {shiftedTime: (now() as LocalDateTime {

<,<=, ==, ~=) and --- "IsIt8?": "Yes", >> |+05:00| ) as LocalDateTime {format "shiftedTime": "2020-04-01T09:12:53.784Z"
{ "IsIt8?" : if( (x>7 and x<9) or (x>=7 and "IsItReallyTrue?": "Yes" : "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"}} }
Logical Operators
x<=8) or (x==8)) "Yes" else }
(and, or, not)
"No","IsItReallyTrue?" : if( strTrue ~= true)
"Yes" else "No"
}

unzip unzip([ ["silver","C"], ["Gold","B"], [["silver","Gold","Platinum"],["C","B"," Shift Timezone output application/java --- { gmtTime: {gmtTime=2020-04-01T04:31:15.416Z[GMT]}
["Platinum","A"]]) A"]] now() >> ("GMT" as TimeZone)}

scan "(510)-456-1234" scan(/([(,),0-9]*)-([0-9]*)- [["(510)-456- Days Difference { Days : (now() - |2019-12- {


([0-9]*)/) 1234","(510)","456","1234"]] 31|)/(24*3600), "Days": 92.0,
Days : daysBetween('2017-10-01', "Days": 31
'2017-11-01') }
}

You might also like