You are on page 1of 53

Data Weave

 Data Weave sections that you have got :


o Input : what’s available for input
o DataWeave code
o Output : shows the preview of the transformation in excpected
output structure
 DW language is json like syntax.
o Header and dw code

Ex :
%dw 1.0
%output application/json
application/xml
application/csv --- Header
--- (divides header and body)
{
orders : {

}
}
 payload and selecting input elements :
Lets take this input :

<?xml version='1.0' encoding='UTF-8'?>


<orders>
<item>
<type>j2se</type>
<price>200</price>
<properties>
<title>Core Java MadeEasy</title>
<authors>
<author>Ratan</author>
</authors>
<year>2014</year>
</properties>
</item>
<item>
<type>j2ee</type>
<price>200</price>
<properties>
<title>Adv Java MadeEasy</title>
<authors>
<author>Ratan</author>
</authors>
<year>2003</year>
</properties>
</item>
</orders>

dw code :
%dw 1.0
%output application/json
---
{
orders : payload.orders.item
}

2
output :
{
"orders": {
"type": "j2se",
"price": "200",
"properties": {
"title": "Core Java MadeEasy",
"authors": {
"author": "Ratan"
},
"year": "2014"
}
}
}
payload.orders.item selects the first item that was with the input

 Where As, payload.orders.*item selects all the items as an array and output
below

{
"orders": [
{
"type": "j2se",
"price": "200",
"properties": {
"title": "Core Java MadeEasy",
"authors": {
"author": "Ratan"
},
"year": "2014"
}
},
{
"type": "j2ee",
"price": "200",
"properties": {
"title": "Adv Java MadeEasy",

3
"authors": {
"author": "Ratan"
},
"year": ""
}
}
]
}

 map operator :
Instead of mapping like payload.orders.*item all items, we can control the
mappings by iterating with map operator :

%dw 1.0
%output application/json
---
{
orders : payload.orders.*item map {
title : $.properties.title,
author : $.properties.authors.author
}
}

Here, map iterates over the items in coming xml.


Use $ symbol to get item under iteration
As DataSense is payload aware , Even we can get autocompletion of elements
while accessing.

Output :
{
"orders": [
{
"title": "Core Java MadeEasy",
"author": "Ratan"
},
{
"title": "Adv Java MadeEasy",
"author": "Ratan"

4
}
]
}

Transformations tags :

De duplicating data 

We can deduplicate data if any :

%dw 1.0
%output application/json
---
{
orders : payload.orders.*item map {
title : $.properties.title,
author : $.properties.authors.author,
authors : $.properties.authors.*author distinctBy $ map {
author : $
}
}
}

Here distinctBy $ , where $ is the value that needs to be distinct as we mean.

5
Output : {
"orders": [
{
"title": "Core Java MadeEasy",
"author": "Ratan",
"authors": [
{
"author": "Ratan"
}
]
},
{
"title": "Adv Java MadeEasy",
"author": "Ratan",
"authors": [
{
"author": "Ratan"
}
]
}]}

6
filter :
We can filter data based on specific value : here below we are filtering by
year

%dw 1.0
%output application/json
---
{
orders : payload.orders.*item filter $.properties.year > 2004 map {
title : $.properties.title,
author : $.properties.authors.author,
authors : $.properties.authors.*author distinctBy $ map {
author : $
}
}
}

Output :
{
"orders": [
{
"title": "Core Java MadeEasy",
"author": "Ratan",
"authors": [
{
"author": "Ratan"
}
]
}
]
}

7
Multiple inputs : using ,

If we want to use any flowVariable inside to iterate/something we can set


configure same as payload metadata in flowVars metadata

Set this below data in flowVars.price :


{
"USD" : [
{"currency" : "EUR" , "ratio" : "0.2" },
{"currency" : "PTK" , "ratio" : "0.4" },
{"currency" : "PND" , "ratio" : "0.6" }
]
}

dw code:
%dw 1.0
%output application/json
---
{ orders : payload.orders.*item filter $.properties.year > 2004 map
using (item = $) {
title : $.properties.title,
author : $.properties.authors.author,
prices : flowVars.price.USD map {
price : $.ratio * item.price,
currency : $.currency
},
authors : $.properties.authors.*author distinctBy $ map {
author : $
}
}}

Here, While iterating flowVar USD , the payload will change , So How to use
item dtaa, for that we can use using operator.
We can refer the main payload with some reference and we can use it anywhere
as, using (item = $).

8
Output :
{ "orders": [
{
"title": "Core Java MadeEasy",
"author": "Ratan",
"prices": [
{
"price": 40.0,
"currency": "EUR"
},
{
"price": 80.0,
"currency": "PTK"
},
{
"price": 120.0,
"currency": "PND"
}
],
"authors": [
{
"author": "Ratan"
}
]}]}

Multiple outputs : ( sizeOf , sum , avg operators )


We can have multiple outputs also, for that click on add symbol on Output
bar where you would need to select Flow/Session/Property var to store o/p of the
outcoming dw code.
%dw 1.0
%output application/csv
---
[{
totalNumberOfitems : sizeOf payload.orders.*item,

9
totalAmount : sum payload.orders.*item.price,
averageSellingPrice : avg payload.orders.*item.price
}]
Here, for application/csv type you would need to enclose it in []
As an array since csv contains multiple values if you miss this you will get an error.
Output :
totalNumberOfitems,totalAmount,averageSellingPrice
2,400,200.0

DataWeave Body :
Body contains expression that generates output structure.
 Model of produced output could consists of one of the following types :
1. Simple Values
2. Arrays (sequence of comma separated values)
3. Objects (Collection of key value pairs)
Simple Values : String( “Hello” / ‘Hello’ ),Boolean (literals true/false ), Number
(2.0 decimal / int ), Date, Regex

Arrays :
%dw 1.0
%output application/json
---
[ "My", "three", "words" ]

Objects. :
These are comma separated sequence of key value pairs surrounded by {}
Ex :
%dw 1.0
%output application/xml
---
myoutput:{
name : "Jill",
payload : payload.id + 3
}

10
Variables :
We can create variables in header and can be used there of in body
Ex : %dw 1.0
%output application/xml
%var language='Español'
---
{
document: {
language: language,
text: "Hola mundo"
}
}

Output :
<?xml version="1.0" encoding="UTF-8"?>
<document>
<language>Español</language>
<text>Hola Mundo</text>
</document>

Scope :
header declared  Global scope
to limit scope  you can declare at any part of dw body
 we can use using(<var-name> : <expression>) operator to declare a var inside
a body
ex :
%dw 1.0
%output application/xml
---
{
person: using (user = "Greg", gender = "male") {
name: user,
gender: gender
}
}

11
Selectors :

Complex structures of objects and arrays can be navigated using selectors


expressions.
 Each selector expression return either Object/Array/simple type
As Data weave processes selectors a new context is set for the further selectors
as you move on
There are 5 types of selector expressions that you can take :
single value : .keyname
 multi value : .*keyname
 indexed : [index]
 attribute : .@attributename
 Descendants : ..keyname
Applying the Single level Explicit Selector, the Descendants Selector, or
the Indexed Selector returns the value of the key:value pair that matches the
expression.

Single valued Selector :


We can use this Over Object/Array input
Ex :

Dw code :

%dw 1.0
%output application/xml
---
{
address: payload.people.person.address
}

12
Input :
{
"people": {
"size" : 1,
"person": {
"name": "Nial",
"address": {
"street": {
"name": "Italia",
"number": 2164
},
"area": {
"zone": "San Isidro",
"name": "Martinez"
}
}
}
}
}

output :

<?xml version="1.0" encoding="UTF-8"?>


<address>
<street>
<name>Italia</name>
<number>2164</number>
</street>
<area>
<zone>San Isidro</zone>
<name>Martinez</name>
</area>
</address>

13
Alternate :
You can also select a single value through the alternate syntax ["<key-name>"]. For
example payload["price"]returns the value whose key matches price. This is valid
for both arrays and objects.

%dw 1.0
%output application/json
---
payload["people"]

or

%dw 1.0
%output application/json
---
payload.items[flowVars.item]

14
Multi Valued :
On either object/Array

%dw 1.0
%output application/json
---
{
users: payload.users.*user
}

Input :
<users>
<user>Mariano</user>
<user>Martin</user>
<user>Leandro</user>
</users>

Output :
{
"users": [
"Mariano",
"Martin",
"Leandro"
]
}

Alternative :
%dw 1.0
%output application/json
---
payload.items[*item]
Indexed :
On Array/Object/String
Returns the element at the specified position.

%dw 1.0
%output application/json

15
---
payload.people[1]

in :
{
"people": [
{
"name": "Nial",
"address": "Martinez"
},
{
"name": "Coty",
"address": "Belgrano"
}
]
}

Out :
{
"name": "Coty",
"address": "Belgrano"
}

 When using the Index Selector with a String, the string is broken down into an
array, where each character is an index.

1 %output application/json
2 ---
3 {
4 name: "MuleSoft"[0]
5 }

16
Output
1 {
2 "name": "M"
3 }

The selector picks the character at a given position, treating the string as an array
of characters.
1. If the index is bigger or equal to 0, it starts counting from the beginning.
2. If the index is negative, it starts counting from the end.

17
Range Selector :
Range selectors limit the output to only the elements specified by the range
on that specific order. This selector allows you to slice an array or even invert it.

1 %dw 1.0
2 %output application/json
3 ---
4 {
5 slice: [0,1,2][0 to 1],
6 last: [0,1,2][-1 to 0]
7 }

Output
1 {
2 "slice": [
3 0,
4 1
5 ],
6 "last": [
7 2,
8 1,
9 0
1 ]
0 }
1
1

Ex :

18
%dw 1.0
%output application/json
---
{
slice : [0,1,2] [0 to 1],
last : [0,1,2] [-1 to 0],
nameslice : "PavanNaidu"[0 to 4],
nameinreverse : "navaP"[-1 to 0]
}

Out:
{
"slice": [
0,
1
],
"last": [
2,
1,
0
],
"nameslice": "Pavan",
"nameinreverse": "Pavan"
}

19
Attribute Selector :
In order to query for the attributes on an Object, the .
@<key-name> is used. If you just use .@ (without <key-name>) it returns an object
containing each key:value pair in it.
Ex :
in:
<product id="1" type="tv">
<brand>Samsung</brand>
2 </product>
3

%dw 1.0
%output application/json
---
{
item: {
type : payload.product.@type,
name : payload.product.brand,
attributes: payload.product.@
}
}
Out:
{
"item:" {
"type": "tv",
"name": "Samsung",
"attributes": {
"id": “1”,
"type": “tv”
}
}
}

20
Selecting the key value pair
As selectors only return the value of a key:value pair, in order to get both the key
and value, you can use a type conversion to object.

1 %dw 1.0
2 %output application/xml
3 ---
4 user: payload.name as :object

In:
1 {
2 "name": "Mariano",
3 "lastName" : "Doe"
4 }

Out:
<?xml version="1.0" encoding="UTF-8"?>
<user>
<name>Mariano</name>
</user>

Without as :object :
o/p
<?xml version='1.0' encoding='UTF-8'?>
<user>Mariano</user>

21
Descendants Selector
This selector is applied to the context using the form ..<field-name> and
retrieves the values of all matching key:value pairs in the sub-tree under the
current context. Regardless of the hierarchical structure these fields are organized
in, they are all placed at the same level in the output.

1 %dw 1.0
2 %output application/json
3 ---
4 {
5 names: payload.people..name
6 }

in:
{
"people": {
"person": {
"name": "Nial",
"address": {
"street": {
"name": "Italia",
"number": 2164
},
"area": {
"zone": "San Isidro",
"name": "Martinez"
}
}
}
}
}

22
Out :
1 {
2 "names": [
3 "Nial",
4 "Italia",
5 "Martinez"
6 ]
7 }

Selecting all the Descendant Key Value Pairs


Transform
1 %dw 1.0
2 %output application/json
3 ---
4 {
5 names: payload.people..name as :object
6 }

out:
{
"names": {
"name": "Nial",
"name": "Italia",
"name": "Martinez"
}
}

23
Selectors Modifiers: ? an !
There are two selectors modifiers: ? and !.
The question mark returns true or false whether the keys are present on the
structures. The exclamation mark evaluates the selection and fails if any key is not
present.

 ? - Returns true if the specified key is present in the object.

1 %dw 1.0
2 %output application/xml
3 ---
4 present: payload.name?

in:
{
"name": "Annie"
2 }
3

out:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <present>true</present>

24
 checking for the attributes like same:
In:
<product id="1" type="tv">
<brand>Samsung</brand>
</product>

%dw 1.0
%output application/json
---
{
item: {
type : payload.product.@type,
name : payload.product.brand,
attributes: payload.product.@,
typePresent : payload.product.@type?
}
}

Out:
{
"item": {
"type": "tv",
"name": "Samsung",
"attributes": {
"id": "1",
"type": "tv"
},
"typePresent": true
}
}
You can also use this(?) validation operation as part of a filter:
In:

1 <users>
2 <name>Mariano</name>
3 <name>Luis</name>
4 <name>Mariano</name>
5 </users>

25
1 %dw 1.0
2 %output application/xml
3 ---
4 users: payload.users.*name[?($ == "Mariano")]

Out:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <users>
3 <name>Mariano</name>
4 <name>Mariano</name>
5 </users>

above selects key:value pairs with value "Mariano" ⇒ {name: Mariano, name:
Mariano}

!:
s an exception if any of the specified keys are not found.
In:
1 {
2 "name": "Annie"
3 }

1 %dw 1.0
2 %output application/xml
3 ---
4 present: payload.lastName!

26
Out:
Exception: "There is no key named 'lastName'" (means warning you can observe)

Reffering elements from muleMessage :

1 %dw 1.0
2 %output application/xml
3 ---
4 {
5 a: inboundProperties.userName
6 }

in header :
%var inUname = inboundProperties['userName']

1 %dw 1.0
2 %output application/xml
3 ---
4 {
5 a: outboundProperties.userName
6 }

%var outUname = outboundProperties['userName']


 flowVars
%dw 1.0
%output application/xml
2 ---
3 {
4 a: flowVars.userName
5 }
6

27
%var uname = flowVars['userName']

 Property :
You can reference any Property (System or Spring) that exists in the server while
DataWeave is processing your transformation, to do so use
the p('prop_name') function.

1 %dw 1.0
2 %output application/xml
3 ---
4 {
5 a: p('userName')
6 }

28
Datweave Types :
 Array :
Type ⇒ ':array'
Arrays are represented as a sequences of value expressions.
[ 1, 2 + 2, 3 * 3, $x ]

Array Literal

1 %dw 1.0
2 %output application/json
3 ---
4 [ "My", "three", "words" ]

Conditional Elements
Arrays can define conditional values based on a condition. Wrap the value
expression between parentheses and use the when keyword with the condition.

1 %dw 1.0
2 %output application/json
3 ---
4 [(1) when true, (2) when false]

Out:
1 [1]

Object :
Type ⇒ ':object'
Objects are represented as a collection of key: value pairs.
1. Object: { 'Key' : Value }
Ex:

29
1 %dw 1.0
2 %output application/xml
3 ---
4 name: "Annie"

Conditional Elements
Objects can define conditional key: value pairs based on a conditional expression.
Wrap the key:value expression between parentheses and use the when keyword
with the condition.

1 %dw 1.0
2 %output application/xml
3 ---
4 file: {
5 name: "transform",
6 (extension: "zip") when payload.fileSystem?
7 }

outputs an additional field called "extension" only when the fileSystem


property is present in payload (this field may contain any value, not just "true").

1 <?xml version="1.0" encoding="UTF-8"?>


2 <file>
3 <name>transform</name>
4 <extension>zip</extension>
5 </file>

If absent:

1 <?xml version="1.0" encoding="UTF-8"?>


2 <file>
3 <name>transform</name>
4 </file>

30
Dynamic Elements
Dynamic elements allow you to add the result of an expression as key:value pairs of
an object.
Transform
1 %dw 1.0
2 %output application/json
3 ---
4 {
5 a: "a",
6 (["b","c","d"] map {'$': $})
7 }

Output
1 {
2 "a": "a",
3 "b": "b",
4 "c": "c",
5 "d": "d"
6 }

Conditional Attributes
attributes can be conditional based on a given condition. Wrap the key:value
expression in parentheses and use the when keyword

1 %dw 1.0
2 %output application/xml
3 ---
4 name @((company: "Acme") when false, (transform: "Anything") when true): "DataWe
ve"
Output
1 <?xml version='1.0' encoding='US-ASCII'?>
2 <name transform="Anything">DataWeave</name>

31
Dynamic Attributes
Dynamic attributes allow you to add the result of an expression as key:value pairs
of the attributes set.
In
1 {
2 "company": "Mule",
3 "product": "DataWeave"
4 }

1 %dw 1.0
2 %output application/xml
3 ---
4 transformation @((payload)): "Transform from anything to anything"

Out
1 <?xml version='1.0' encoding='US-ASCII'?>
2 <transformation company="Mule" product="DataWeave">Transform from anything to
sformation>

String :
‘:string’

{
doubleQuoted: "Hello",
singleQuoted: 'Hello',
}

32
To use vars inside string :
1 %dw 1.0
2 %output application/json
3 %var name = "Shoki"
4 ---
5 {
6 Greeting: "Hi, my name is $name",
7 Sum: "1 + 1 = $(1 + 1)"
8 }

Out:
1 {
2 "Greeting": "Hi, my name is Shoki",
3 "Sum": "1 + 1 = 2"
4 }

Number :
‘:number’
 only number type that supports int and float
 no compromise in precision
Boolean :
:Boolean (true / false)

Dates :
DW dates follow ISO-8601 defined |xxxx|.
 date |YYYY-MM-DD|, time |HH:MM:SS:MS|, timeZone |+HH:MM|
 DateTime : date + time + timeZone

Date :
:date Represented as 'Year'-'Month'-'Date'
%dw 1.0
%output application/json
---
c: |2003-10-01|

33
out:
{
"c": "2003-10-01"
2 }
3

Time : :
time s 'Hour':'Minutes':'Seconds'.'Milliseconds'

1 %dw 1.0
2 %output application/json
3 ---
4 c: |23:59:56|

Out:
1 {
2 "c": "23:59:56"
3 }

TimeZone :
:timeZone must include +/- to differentiate to :time
1 %dw 1.0
2 %output application/json
3 ---
4 c: |-08:00|

34
Output
1 {
2 "c": "-08:00"
3 }

DateTime : :datetime
is the conjunction of 'Date' + 'Time' + 'TimeZone'.

1 %dw 1.0
2 %output application/json
3 ---
4 a: |2003-10-01T23:57:59-03:00|

Output
1 {
2 "a": "2003-10-01T23:57:59-03:00"
3 }

LocalDateTime. : :localdatetime
is the conjunction of 'Date' + 'Time'.
1 %dw 1.0
2 %output application/json
3 ---
4 a: |2003-10-01T23:57:59|

Output
1 {
2 "a": "2003-10-01T23:57:59"
3 }

35
Special methods :

1 %dw 1.0
2 %output application/json
3 ---
4 {
5 day: |2003-10-01T23:57:59Z|.day,
6 month: |2003-10-01T23:57:59Z|.month,
7 year: |2003-10-01T23:57:59Z|.year,
8 hour: |2003-10-01T23:57:59Z|.hour,
9 minutes: |2003-10-01T23:57:59Z|.minutes,
1 seconds: |2003-10-01T23:57:59Z|.seconds,
0 offsetSeconds: |2003-10-01T23:57:59-03:00|.offsetSeconds,
1 nanoseconds: |23:57:59.700|.nanoseconds,
1 milliseconds: |23:57:59.700|.milliseconds,
1 dayOfWeek: |2003-10-01T23:57:59Z|.dayOfWeek,
2 dayOfYear: |2003-10-01T23:57:59Z|.dayOfYear
1 }
3
1
4
1
5
1
6

Out:
{
"day": 1,
"month": 10,
"year": 2003,
"hour": 23,
"minutes": 57,
"seconds": 59,
"offsetSeconds": -10800,
"nanoseconds": 700000000,

36
"milliseconds": 700,
"dayOfWeek": 3,
"dayOfYear": 274
}

Formatting dates :
 As :string

1 %dw 1.0
2 %output application/json
3 ---
4 formatedDate: |2003-10-01T23:57:59| as :string {format: "YYYY-MM-dd"}

Out:
1 {
2 "formatedDate": "2003-10-01"
3 }

 header declared : Custom Type


1 %dw 1.0
2 %output application/json
3 %type mydate = :string { format: "YYYY/MM/dd" }
4 ---
5 {
6 formatedDate1: |2003-10-01T23:57:59| as :mydate,
7 formatedDate2: |2015-07-06T08:53:15| as :mydate
8 }

 formatedDate2: "2017-03-12" as :date { format : "yyyyMM-dd"}


as :string {format : "YYYYMMdd"}

37
Custom Types :

%type name = java definition

Ex :
%dw 1.0
%type currency = :number { format: "##"}
%type user = :object { class: “my.company.User”}

Ex2 :
%dw 1.0
%output application/json
2 %type currency = :number { format: "##"}
3 ---
4 books: payload.items.*item map
5 book:
6 price: $.price as :currency
7

38
Functions and lamdas :
can define a function as a variable with a constant directive through '%var'

1 %dw 1.0
2 %output application/json
3 %var toUser = (user) -> {firstName: user.givenName, lastName: user.sn}
4 ---
5 {
6 "user" : toUser({ givenName : "Annie", sn : "Point" })
7 }

Output
1 {
2 "user": {
3 "firstName": "Annie",
4 "lastName": "Point"
5 }
6 }

Declaring same using function directive.

Transform
1 %dw 1.0
2 %output application/json
3 %function toUser(user){firstName: user.givenName, lastName: user.sn}
4 ---
5 {
6 "user" : toUser({ givenName : "Annie", sn : "Point" })
7 }

Output
1 {

39
2 "user": {
3 "firstName": "Annie",
4 "lastName": "Point"
5 }
6 }

Operators on any type : typeOf , as , +


On Numer : +, - , / , * we can check this in operators more…

Operators :
There are difft types of operators some of them we already know,
map/sozeOf/+/- …etc

Map Operator : map we can use in difft ways :

Case1 : to retun array

%dw 1.0
%output application/json
---
users: ["john", "peter", "matt"] map upper $

{
"users": [
"JOHN",
"PETER",
"MATT"
]
}

40
Case2: map as an Object
Return array with values as result after applying transformations to each
values in the coming object.

<prices>
<basic>9.99</basic>
<premium>53</premium>
<vip>398.99</vip>
</prices>

%dw 1.0
%output application/json
%var conversionRate=13.45
---
priceList: payload.prices map (
'$$':{
dollars: $,
localCurrency: $ * conversionRate
}
)

{
"priceList": [
{
"0": {
"dollars": "9.99",
"localCurrency": 134.3655
}
},
{
"1": {
"dollars": "53",
"localCurrency": 712.85
}
},
{
"2": {
"dollars": "398.99",
"localCurrency": 5366.4155
}
}
]
}

mapObject :

41
using mapObject we can get keys also ($$) but not from map operator

diff b/w map and mapObject :

 map you can not get keyNames if you need unless you use pluck
mapObject you can get both keys and values with $$ and $

Map : you can see above page


MapObject:

<prices>
<basic>9.99</basic>
<premium>53</premium>
<vip>398.99</vip>
</prices>

%dw 1.0
%output application/json
%var conversionRate=13.45
---
priceList: payload.prices mapObject(
'$$':{
dollars: $,
localCurrency: $ * conversionRate
}
)

{
"priceList": {
"basic": {
"dollars": "9.99",
"localCurrency": 134.3655
},
"premium": {
"dollars": "53",
"localCurrency": 712.85
},
"vip": {
"dollars": "398.99",
"localCurrency": 5366.4155
}
}
}

Pluck :

42
Pluck is useful when mapping an object  array
Pluck is alternate mapping mechanism to mapObject
With map operator you can’t get keys : But by using pluck $$ you can get
array of keys at that point

It executes on a key-val pair of an in object and returns array (either $$


keys, or values $)

<prices>
<basic>9.99</basic>
<premium>53</premium>
<vip>398.99</vip>
</prices>

%dw 1.0
%output application/json
---
result: {
keys: payload.prices pluck $$,
values: payload.prices pluck $
}

{
"result": {
"keys": [
"basic",
"premium",
"vip"
],
"values": [
"9.99",
"53",
"398.99"
]
}
}

Filter :
Case 1 : using filter on array
Returns array satisfying the filter expression,
Expression is followed by either key $$ or value $

43
%dw 1.0
%output application/json
---
{
biggerThanTwo: [0, 1, 2, 3, 4, 5] filter $ > 2
}

{
"biggerThanTwo": [3,4,5]
}

Case2: filter on object


Returns an object with key value pairs that satisfies filter expression
Expression is followed by either key $$ or value $

 prior to the transformation:


[
{"data": "a"},
{"data": "b"},
{"data": "c"},
{"data": "d"}
]

%dw 1.0
%output application/json
---
filtered: (payload filter ($.*data contains "b") map {
data: $.data
})

{
"filtered": [
{
"data": "b"
}
]
}

 after the transform:

%dw 1.0
%output application/xml
---
filtered: {
aa: "a", bb: "b", cc: "c", dd: "d"
} filter $ == "d"

44
<?xml version="1.0" encoding="UTF-8"?>
<filtered>
<dd>d</dd>
</filtered>

Filter by key : But here filter will not work you would have to use mapObject and
when

%dw 1.0
%output application/json
---
filtered: {
aa: "a", bb: "b", cc: "c", dd: "d"
} mapObject ({ ($$): $ } when $$ as :string == "dd" otherwise {})

{
"filtered": {
"dd": "d"
}
}

Remove :
On Array, it will return array with the specified val removed.

%dw 1.0
%output application/json
---
{
aa: ["a", "b", "c"] - "b"
}

{
"aa": ["a", "c"]
}

 on Object :

%dw 1.0
%output application/json
---
myObject: {aa: "a", bb: "b"} - "aa"

 by matching key and value:

45
%dw 1.0
%output application/json
---
myObject: {aa: "a", aa:"c", bb: "b"} -- { aa:"a"}

{
"myObject": {
"aa": "c",
"bb": "b"} }
%dw 1.0
%output application/json
---
{
removeKeyValPair : {
"aa" : "AAA",
"zz" : "ZZZ",
"bb" : "BBB"
} -- {"zz" : "ZZZ" , "aa" : "AAA"}
}

{
"removeKeyValPair": {
"bb": "BBB"
}
}

And / or :

 and / or

%dw 1.0
%output application/json
---
{
Andcondition : {
Andcurrency: "USD"
} when payload.prices.country == "USA" and
payload.prices.currency == "local"
otherwise
{
Andcurrency: "EUR"
},

OrCondition : {
country : "IND"
} when payload.prices.country == "USA" or payload.prices.currency
== "EUR"
otherwise {
country : "PAK"
}
}

46
Is :
Evaluates a condition and returns Boolean

<root>
<order>
<items> 155 </items>
</order>
<order>
<items> 30 </items>
</order>
<order>
null
</order>
</root>

%dw 1.0
%output application/xml
---
ROOT: payload.root.*order mapObject (
ORDER:{
itemsCollectionPresent: $ is :object and $.items?
}
)

Concat :

Case1: on Array :

%dw 1.0
%output application/json
---
{
a: [0, 1, 2] ++ [3, 4, 5]
}

47
"a": [0, 1, 2, 3, 4, 5]
}

Case2: on String

%dw 1.0
%output application/json
---
{
name: "Mule" ++ "Soft"
}

{
"name": MuleSoft
}

Case3 : on object

%dw 1.0
%output application/xml
---
concat: {aa: "a"} ++ {cc: "c"}

<?xml version="1.0" encoding="UTF-8"?>


<concat>
<aa>a</aa>
<cc>c</cc>
</concat>

Contains: checks for a given value in coming list/array :

Case1 : on Array

<?xml version="1.0" encoding="UTF-8"?>


<root>
<order>
<items>155</items>
</order>
<order>
<items>30</items>
</order>
<order>

48
<items>15</items>
</order>
<order>
<items>5</items>
</order>
<order>
<items>4</items>
<items>7</items>
</order>
<order>
<items>1</items>
<items>3</items>
</order>
<order>
null
</order>
</root>

%dw 1.0
%output application/json
---
ContainsRequestedItem: payload.root.*order.*items contains "3"

{
"ContainsRequestedItem": true
}

Case2 : On String

<?xml version="1.0" encoding="UTF-8"?>


<root>
<mystring>some string</mystring>
</root>

%dw 1.0
%output application/json
---
ContainsString: payload.root.mystring contains "me"

49
{
"ContainsString": true
}

Or on reg expression also

<?xml version="1.0" encoding="UTF-8"?>


<root>
<mystring>A very long string</mystring>
</root>

%dw 1.0
%output application/json
---
ContainsString: payload.root.mystring contains /s[t|p]ring/`

{
"ContainsString": true
}

Type Coercion using “as” :


Case1 : to string :
Any simple type can be converted to string, incase if formatting reqd then you
need to use schema format property {format : “xxxxxx”}

%dw 1.0
%output application/json
---
{
a: 1 as :string {format: "##,#"},
b: now as :string {format: "yyyy-MM-dd"},
c: true as :string
}

50
{
"a": "1",
"b": "2015-07-07",
"c": "true"
}

Case2: to number

%dw 1.0
%output application/json
---
{
a: "1" as :number
}

Case3: date to number

%dw 1.0
%output application/json
---
{
mydate1: |2005-06-02T15:10:16Z| as :number {unit: "seconds"},
mydate2: |2005-06-02T15:10:16Z| as :number {unit: "milliseconds"}
}

{
"mydate1": 1117725016,
"mydate2": 1117725016000
}

Only seconds/milliseconds is allowed for unit

Case4 : StringFormat to localdatetime :

%dw 1.0
%output application/json
---
{
a: 1436287232 as :datetime,
b: "2015-10-07 16:40:32.000" as :localdatetime {format: "yyyy-MM-dd HH:mm:ss.SSS"}
}

{
"a": "2015-07-07T16:40:32Z",
"b": "2015-10-07 16:40:32.000"
}

51

%output application/json
---
{
myDate: ((payload as :string) as :date {format: "yyyyMMdd"}) as :string {format: "MM-dd-yyyy"}
}

Case5: to Object

%dw 1.0
%output application/json
---
{
payload as :object {class : "soa.sfabs.SOAResponseInfoType\$ServiceInfo"}
}

typeOf :
to find the type of the incoming element/message

{
"mystring":"a string"
}

%dw 1.0
%output application/json
---
isString: typeOf payload.mystring

{
"isString": ":string"
}
Flatten : flatten
To convert array of arrays into single array

[
[3,5],
[9,5],
[154,0.3]
]

%dw 1.0
%output application/json
---
flatten payload

52
3,
5,
9,
5,
154,
0.3
]

sizeOf : to find the length of array/object/string

%dw 1.0
%output application/json
---
{
arraySize: sizeOf [1,2,3],
textSize: sizeOf "MuleSoft",
objectSize: sizeOf {a:1,b:2}
}

{
"arraySize": 3,
"textSize": 8,
"objectSize": 2
}

Avg :
%dw 1.0
%output application/json
---
{
a: avg [1..1000],
b: avg [1, 2, 3]
}

{
"a": 500.5,
"b": 2.0
}

joinBy /splitBy/orderBy/groupBy/distinctBy :

53

You might also like