1. dw::Core
This module contains all the core data weave functionality. It is automatically imported into any DataWeave script.
1.1. Functions
1.1.1. ++
++(Array<S>, Array<T>): Array<S | T>
Concatenates the elements of two arrays into a new array.
If the two arrays contain different types of elements, the resulting array
is all of S
type elements of Array<S>
followed by all the T
type elements
of Array<T>
. Either of the arrays can also have mixed-type elements.
The example concatenates an Array<Number>
with an Array<String>
.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
result: [0, 1, 2] ++ ["a", "b", "c"]
}
1
2
3
{
"result": [0, 1, 2, "a", "b", "c"]
}
Note that the arrays can contain any supported data type, for example:
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
a: [0, 1, true, "my string"] ++ [2, [3,4,5], {"a": 6}]
}
1
2
3
{
"a": [0, 1, true, "my string", 2, [3, 4, 5], { "a": 6}]
}
++(String, String): String
Concatenates the characters of two strings.
Strings are treated as arrays of characters, so the ++
operator concatenates
the characters of each String as if they were arrays of single character String.
In the example, the String 'Mule' is treated as Array<String> ['M', 'u', 'l', 'e']
.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
name: 'Mule' ++ 'Soft'
}
1
2
3
{
'name': MuleSoft
}
++(Object, Object): Object
Concatenates two input objects and returns one flattened object.
The ++
operator extracts all the key-values pairs from each object,
then combines them together into one result object.
1
2
3
4
%dw 2.0
output application/xml
---
concat: {aa: 'a', bb: 'b'} ++ {cc: 'c'}
1
2
3
4
5
6
<?xml version='1.0' encoding='UTF-8'?>
<concat>
<aa>a</aa>
<bb>b</bb>
<cc>c</cc>
</concat>
If you leave the output as application/dw
, the example above concatenates
each key-value pair from the two objects {aa: 'a', bb: 'b'} ++ {cc: 'c'}
and
returns a single object {aa: 'a' , bb: 'b', cc: 'c'}
.
++(Date, LocalTime): LocalDateTime
Appends a LocalTime
with a Date
object and returns a more precise
LocalDateTime
value.
Date
and LocalTime
instances are written in standard Java notation,
surrounded by pipe (|
) symbols. The result is a LocalDateTime
object
in the standard Java format.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
a: |2003-10-01| ++ |23:57:59|,
b: |2003-10-01| ++ |23:57:59Z|
}
1
2
3
4
{
'a': '2003-10-01T23:57:59',
'b': '2003-10-01T23:57:59Z'
}
Note that the order in which the two objects are concatenated is irrelevant, so
logically, Date
+ LocalTime
produces the same result as LocalTime
+ Date
.
++(LocalTime, Date): LocalDateTime
Appends a LocalTime
with a Date
object and returns a more precise
LocalDateTime
value.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
a: |23:57:59| ++ |2003-10-01|,
b: |23:57:59Z| ++ |2003-10-01|
}
1
2
3
4
{
'a': '2003-10-01T23:57:59',
'b': '2003-10-01T23:57:59Z'
}
Note that the order in which the two objects are concatenated is irrelevant, so
logically, LocalTime
+ Date
produces the same result as Date
+ LocalTime
.
++(Date, Time): DateTime
Appends a Date
to a Time
object and returns a more precise DateTime
value.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
a: |2003-10-01| ++ |23:57:59|,
b: |2003-10-01| ++ |23:57:59Z|
}
1
2
3
4
{
'a': '2003-10-01T23:57:59',
'b': '2003-10-01T23:57:59Z'
}
Note that the order in which the two objects are concatenated is irrelevant,
so logically, Date
+ Time
produces the same result as Time
+ Date
.
++(Time, Date): DateTime
Appends a Date
to a Time
object to return a more precise DateTime
value.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
a: |23:57:59| ++ |2003-10-01|,
b: |23:57:59Z| ++ |2003-10-01|
}
1
2
3
4
{
'a': '2003-10-01T23:57:59',
'b': '2003-10-01T23:57:59Z'
}
Note that the order in which the two objects are concatenated is irrelevant,
so logically, Date
+ Time
produces the same result as a Time
+ Date
.
++(Date, TimeZone): DateTime
Appends a TimeZone
to a Date
type value and returns a DateTime
result.
1
2
3
4
%dw 2.0
output application/json
---
a: |2003-10-01T23:57:59| ++ |-03:00|
1
2
3
{
'a': '2003-10-01T23:57:59-03:00'
}
++(TimeZone, Date): DateTime
Appends a Date
to a TimeZone
type value and returns a DateTime
result.
1
2
3
4
%dw 2.0
output application/json
---
a: |-03:00| ++ |2003-10-01T23:57:59|
1
2
3
{
'a': '2003-10-01T23:57:59-03:00'
}
++(LocalDateTime, TimeZone): DateTime
Appends a TimeZone
to a LocalDateTime
type value and returns a DateTime
result.
1
2
3
4
%dw 2.0
output application/json
---
a: |2003-10-01T23:57:59| ++ |-03:00|
1
2
3
{
'a': '2003-10-01T23:57:59-03:00'
}
++(TimeZone, LocalDateTime): DateTime
Appends a LocalDateTime
to a TimeZone
type value and returns a DateTime
result.
1
2
3
4
%dw 2.0
output application/json
---
a: |-03:00| ++ |2003-10-01T23:57:59|
1
2
3
{
'a': '2003-10-01T23:57:59-03:00'
}
++(LocalTime, TimeZone): Time
Appends a TimeZone
to a LocalTime
type value and returns a Time
result.
1
2
3
4
%dw 2.0
output application/json
---
a: |2003-10-01T23:57:59| ++ |-03:00|
1
2
3
{
'a': '2003-10-01T23:57:59-03:00'
}
++(TimeZone, LocalTime): Time
Appends a LocalTime
to a TimeZone
type value and returns a Time
result.
1
2
3
4
%dw 2.0
output application/json
---
a: |-03:00| ++ |2003-10-01T23:57:59|
1
2
3
{
'a': '2003-10-01T23:57:59-03:00'
}
1.1.2. —
--(Array<S>, Array<Any>): Array<S>
Returns a new array that removes every occurrence of elements listed in the
right-hand side (rhs
) array from the left-hand side (lhs
) array. The result
is that same as iteratively taking lhs - elementN
, for each elementN
in rhs
.
When an element in the lhs
array matches one of the values in the rhs
array,
it is removed. If multiple elements in the lhs
array match a value, all matching
values are removed from the
lhs
.
1
2
3
4
%dw 2.0
output application/json
---
a: [0, 1, 1, 2] -- [1,2]
1
2
3
{
"a": [0],
}
--({ (K)?: V }, Object): { (K)?: V }
Removes all the entries from the source that are present on the toRemove
parameter.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
hello: 'world',
name: "DW"
} -- {hello: 'world'}
1
2
3
{
"name": "DW"
}
--(Object, Array<String>)
Removes the properties from the source that are present the given list of keys.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
hello: 'world',
name: "DW"
} -- ['hello']
1
2
3
{
"name": "DW"
}
--(Object, Array<Key>)
Removes the properties from the source that are present the given list of keys.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
hello: 'world',
name: "DW"
} -- ['hello' as Key]
1
2
3
{
"name": "DW"
}
1.1.3. abs
abs(Number): Number
Returns the absolute value of a number.
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
---
{
a: abs(-2),
b: abs(2.5),
c: abs(-3.4),
d: abs(3)
}
1
2
3
4
5
6
{
"a": 2,
"b": 2.5,
"c": 3.4,
"d": 3
}
1.1.4. avg
avg(Array<Number>): Number
Creates an average of all the values in an array and outputs a single number. The array must of course contain only numerical value in it.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
a: avg([1, 1000]),
b: avg([1, 2, 3])
}
1
2
3
4
{
"a": 500.5,
"b": 2.0
}
1.1.5. ceil
ceil(Number): Number
Rounds a number upwards, returning the first full number above than the one provided.
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
---
{
a: ceil(1.5),
b: ceil(2.2),
c: ceil(3)
}
1
2
3
4
5
{
"a": 2,
"b": 3,
"c": 3
}
1.1.6. contains
contains(Array<T>, Any): Boolean
Indicates whether an array contains a given value. Returns true
or false
.
1
2
3
4
%dw 2.0
output application/json
---
ContainsRequestedItem: payload.root.*order.*items contains "3"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="UTF-8"?>
<root>
<order>
<items>155</items>
</order>
<order>
<items>30</items>
</order>
<order>
<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>
1
2
3
{
"ContainsRequestedItem": true
}
contains(String, String): Boolean
Indicates whether a string contains a given substring. Returns true
or false
.
1
2
3
4
%dw 2.0
output application/json
---
ContainsString: payload.root.mystring contains "me"
1
2
3
4
<?xml version="1.0" encoding="UTF-8"?>
<root>
<mystring>some string</mystring>
</root>
1
2
3
{
"ContainsString": true
}
contains(String, Regex): Boolean
Indicates whether a string contains a match to a given regular expression. Returns true
or false
.
1
2
3
4
%dw 2.0
output application/json
---
ContainsString: payload.root.mystring contains /s[t|p]rin/
1
2
3
4
<?xml version="1.0" encoding="UTF-8"?>
<root>
<mystring>A very long string</mystring>
</root>
1
2
3
{
"ContainsString": true
}
1.1.7. daysBetween
daysBetween(Date, Date): Number
Returns the number of days between two dates.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
"days": daysBetween("2016-10-01T23:57:59-03:00", "2017-10-01T23:57:59-03:00")
}
1
2
3
{
"days": 365
}
1.1.8. distinctBy
distinctBy(Array<T>, (item: T, index: Number) → Any): Array<T>
Returns only unique values from an array that may have duplicates.
The lambda is invoked with two parameters: value
and index
.
If these parameters are not defined, the index is defined by default as $$
and the value as $
.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
output application/json
---
{
book : {
title : payload.title,
year: payload.year,
authors: payload.author distinctBy $
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"title": "XQuery Kick Start",
"author": [
"James McGovern",
"Per Bothner",
"Kurt Cagle",
"James Linn",
"Kurt Cagle",
"Kurt Cagle",
"Kurt Cagle",
"Vaidyanathan Nagarajan"
],
"year":"2000"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"book": {
"title": "XQuery Kick Start",
"year": "2000",
"authors": [
"James McGovern",
"Per Bothner",
"Kurt Cagle",
"James Linn",
"Vaidyanathan Nagarajan"
]
}
}
distinctBy({ (K)?: V }, (value: V, key: K) → Any): Object
Returns an object with unlike key value pairs.
The function (a lambda) is invoked with two parameters: value
and key
.
If these parameters are not defined, the index is defined by default as $$
and the value as $`
.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/xml
---
{
book : {
title : payload.book.title,
authors: payload.book.&author distinctBy $
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<book>
<title> "XQuery Kick Start"</title>
<author>
James Linn
</author>
<author>
Per Bothner
</author>
<author>
James McGovern
</author>
<author>
James McGovern
</author>
<author>
James McGovern
</author>
</book>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<book>
<title> "XQuery Kick Start"</title>
<authors>
<author>
James Linn
</author>
<author>
Per Bothner
</author>
<author>
James McGovern
</author>
</authors>
</book>
1.1.9. endsWith
endsWith(String, String): String
Returns true or false depending on if a string ends with a provided substring.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
a: "Mariano" endsWith "no",
b: "Mariano" endsWith "to"
}
1
2
3
4
{
"a": true,
"b": false
}
1.1.10. filter
filter(Array<T>, (item: T, index: Number) → Boolean): Array<T>
Returns an array that containing elements that meet the criteria specified
by a function (a lambda). The function is invoked with two parameters: value
and index
.
If the parameters are not named, the index is defined by default as $$
, and
the value is $
. In the next example, the value ($
) in the returned array
must be greater than 2
.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
biggerThanTwo: [1, 2, 3, 4, 5] filter($ > 2)
}
1
2
3
{
'biggerThanTwo': [3,4,5]
}
In the next example, the index ($$
) of the returned array must be greater
than 2
.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
indexBiggerThanTwo: [1, 2, 3, 4, 5] filter($$ > 2)
}
1
2
3
{
'indexBiggerThanTwo': [4,5]
}
The next example passes named key and value parameters.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
example3: [0, 1, 2, 3, 4, 5] filter ((key1, value1) -> key1 > 3 and value1 < 5 )
}
1
2
3
{
'example3': [4]
}
filter(Null, (item: Nothing, index: Nothing) → Boolean): Null
Helper function that allows filter
to work with null values.
1.1.11. filterObject
filterObject({ (K)?: V }, (value: V, key: K, index: Number) → Boolean): { (K)?: V }
Returns an object that filters an input object based on a matching condition.
The function (a lambda) is invoked with three parameters: value
, key
, and
index
. If these parameters are not named, the value is defined by default as
$
, the key $$
and the index $$$
.
This example filters an object by its value.
1
2
3
4
%dw 2.0
output application/json
---
{'letter1': 'a', 'letter2': 'b'} filterObject ((value1) -> value1 == 'a')
1
2
3
{
'letter1': 'a'
}
You can produce the same results with this input:
1
2
3
4
%dw 2.0
output application/json
---
{'letter1': 'a', 'letter2': 'b'} filter ($ == 'a')
filterObject(Null, (value: Nothing, key: Nothing, index: Nothing) → Boolean): Null
Helper function that allows filterObject
to work with null values.
1.1.12. find
find(Array<T>, Any): Array<Number>
Returns the array of index where the element to be found where present
1
2
3
4
%dw 2.0
output application/json
---
["name", "lastName"] find "name"
1
2
3
[
0
]
find(String, Regex): Array<Array<Number>>
Returns the array of index where the regex matched in the text
1
2
3
4
%dw 2.0
output application/json
---
"DataWeave" find /a/
1
2
3
[
[1], [3], [6]
]
find(String, String): Array<Number>
Given a string, it returns the index position within the string at which a match was matched. If found in multiple parts of the string, it returns an array with the various idex positions at which it was found. You can either look for a simple string or a regular expression.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: "aabccde" find /(a).(b)(c.)d/,
b: "aabccdbce" find "a",
c: "aabccdbce" find "bc"
}
1
2
3
4
5
{
"a": [[0,0,2,3]],
"b": [0,1],
"c": [2,6]
}
1.1.13. flatMap
flatMap(Array<T>, (item: T, index: Number) → Array<R>): Array<R>
Maps an array of items using the specified callback
and applies flatten
to the resulting array.
1
2
3
4
%dw 2.0
output application/json
---
users: ['john', 'peter', 'matt'] flatMap([$$ as String, $])
1
2
3
4
5
6
7
8
9
10
{
'users': [
'0',
'john',
'1',
'peter',
'2',
'matt'
]
}
flatMap(Null, (Nothing, Nothing) → Any): Null
Helper function that allows flatMap
to work with null values.
1.1.14. flatten
flatten(Array<Array<T> | Q>): Array<T | Q>
If you have an array of arrays, this operator can flatten it into a single simple array.
1
2
3
4
%dw 2.0
output application/json
---
flatten(payload)
1
2
3
4
5
[
[3,5],
[9,5],
[154,0.3]
]
1
2
3
4
5
6
7
8
[
3,
5,
9,
5,
154,
0.3
]
1.1.15. floor
floor(Number): Number
Rounds a number downwards, returning the first full number below the one provided.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: floor(1.5),
b: floor(2.2),
c: floor(3)
}
1
2
3
4
5
{
"a": 1,
"b": 2,
"c": 3
}
1.1.16. groupBy
groupBy(Array<T>, (item: T, index: Number) → R): { ®: Array<T> }
Partitions an Array into a Object that contains Arrays, according to the discriminator function (a lambda) that you define.
The lambda is invoked with three parameters: value
, key
, and index
.
If these parameters are not named, the value is defined by default as $
,
the key $$
and the index $$$
.
1
2
3
4
%dw 2.0
output application/json
---
"language": payload.langs groupBy $.language
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"langs": [
{
"name": "Foo",
"language": "Java"
},
{
"name": "Bar",
"language": "Scala"
},
{
"name": "FooBar",
"language": "Java"
}
]
}
1
2
3
4
5
6
7
8
9
10
11
{
"language": {
"Scala": [
{"name":"Bar", "language":"Scala"}
],
"Java": [
{"name":"Foo", "language":"Java"},
{"name":"FooBar", "language":"Java"}
]
}
}
groupBy({ (K)?: V }, (value: V, key: K) → R): { ®: Array<T> }
Partitions an Object
into a Object
that contains Arrays
, according to
the discriminator lambda you define.
The lambda is invoked with two parameters: value
and the key
.
groupBy(Null, (Nothing, Nothing) → Any): Null
Helper function that allows groupBy to work with null values.
1.1.17. isBlank
isBlank(String): Boolean
Returns true
if it receives a string composed of only whitespace characters.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
empty: isBlank(""),
withSpaces: isBlank(" "),
withText: isBlank(" 1223")
}
1
2
3
4
5
{
"empty": true,
"withSpaces": true,
"withText": false
}
1.1.18. isDecimal
isDecimal(Number): Boolean
Returns true
if it receives a number that has any decimals in it.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
decimal: isDecimal(1.1),
integer: isDecimal(1)
}
1
2
3
4
{
"decimal": true,
"integer": false
}
1.1.19. isEmpty
isEmpty(Array<Any>): Boolean
Returns true
or false
depending on whether an array is empty.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
empty: isEmpty([]),
nonEmpty: isEmpty([1])
}
1
2
3
4
{
"empty": true,
"nonEmpty": false
}
isEmpty(String): Boolean
Returns true
or false
depending on whether a string is empty.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
empty: isEmpty(""),
nonEmpty: isEmpty("DataWeave")
}
1
2
3
4
{
"empty": true,
"nonEmpty": false
}
isEmpty(Object): Boolean
Returns true
or false
depending on whether an object is empty.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
empty: isEmpty({}),
nonEmpty: isEmpty({name: "DataWeave"})
}
1
2
3
4
{
"empty": true,
"nonEmpty": false
}
1.1.20. isEven
isEven(Number): Boolean
Returns true if the specified number is Even.
1.1.21. isInteger
isInteger(Number): Boolean
Returns true is the number doesn’t have any decimals.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
decimal: isInteger(1.1),
integer: isInteger(1)
}
1
2
3
4
{
"decimal": false,
"integer": true
}
1.1.22. isLeapYear
isLeapYear(DateTime): Boolean
Returns true
if it receives a DateTime
for a leap year.
isLeapYear(Date): Boolean
Returns true
if it receives a Date
for a leap year.
isLeapYear(LocalDateTime): Boolean
Returns true
if it receives a LocalDateTime
for a leap year.
1.1.23. isOdd
isOdd(Number): Boolean
Returns true if the specified number is Odd.
1.1.24. joinBy
joinBy(Array<Any>, String): String
Merges an array into a single string value, using the provided string as a separator between elements.
1
2
3
4
%dw 2.0
output application/json
---
aa: ["a","b","c"] joinBy "-"
1
2
3
{
"aa": "a-b-c"
}
1.1.25. log
log(String, T): T
Logs the specified value with a given prefix
. Then it returns the
value unchanged.
1
2
3
4
%dw 2.0
payload application/json
---
{ age: log("My Age", payload.age) }
1
{ "age" : 33 }
This will print this output: My Age - 33
.
1
<age>33</age>
Note that besides producing the expected output, it also logs it.
1.1.26. lower
lower(String): String
Returns the provided string in lowercase characters.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
name: lower("MULESOFT")
}
1
2
3
{
"name": "mulesoft"
}
1.1.27. map
map(Array<T>, (item: T, index: Number) → R): Array<R>
Iterates over each item in an array and returns the array of items that results from applying a transformation function to the elements.
The function (a lambda) is invoked with the value
and the index
parameters.
In the following example, custom names are defined for these parameters. Then
both are used to construct the returned value. In this case, value is defined
as firstName
, and its index is defined as position
.
1
2
3
4
%dw 2.0
output application/json
---
users: ['john', 'peter', 'matt'] map ((firstName, position) -> position ++ ':' ++ upper(firstName))
1
2
3
4
5
6
7
{
'users': [
'0:JOHN',
'1:PETER',
'2:MATT'
]
}
If the parameters to map
are not named, the index is defined by default as
$$
, and the value is $
. The next example produces the same output as the
script above. Note that the selector for the key in the next example must be
surrounded by parentheses (for example, ($$)
).
%dw 2.0 output application/json --- users: ['john', 'peter', 'matt'] map (($$) ++ ':' ++ upper($))
This next transformation script produces an array of objects from an input array.
1
2
3
4
%dw 2.0
output application/json
---
payload.users map { ($$) : upper($) }
{ 'users' : ['fer', 'steven', 'lorraine', 'george'] }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
{
'0': 'FER'
},
{
'1': 'STEVEN'
},
{
'2': 'LORRAINE'
},
{
'3': 'GEORGE'
}
]
map(Null, (Nothing, Nothing) → Any): Null
Helper function that allows map
to work with null values.
1.1.28. mapObject
mapObject({ (K)?: V }, (V, K, Number) → Object): Object
Iterates through key-value pairs within an object and returns an object. You can retrieve the key, value, or index of any key-value pair in the object.
This function is similar to map
. However, instead of processing only values
of an object, mapObject
processes both keys and values as a tuple. Also,
instead of returning an array with the results of processing these values
through the function, it returns an object, which consists of a list of the
key-value pairs that result from processing both key and value of the object
through the function (a lambda).
The function is invoked with three parameters: value
, key
and the index
.
The third parameter, index
, is optional.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
output application/json
var conversionRate=13
---
priceList: payload.prices mapObject(value, key, index) -> {
(key) : {
dollars: value,
localCurrency: value * conversionRate,
index_plus_1: index + 1
}
}
1
2
3
4
5
<prices>
<basic>9.99</basic>
<premium>53</premium>
<vip>398.99</vip>
</prices>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
'priceList': {
'basic': {
'dollars': '9.99',
'localCurrency': 129.87,
'index_plus_1': 1
},
'premium': {
'dollars': '53',
'localCurrency': 689,
'index_plus_1': 2
},
'vip': {
'dollars': '398.99',
'localCurrency': 5186.87,
'index_plus_1': 3
}
}
}
For each key-value pair in the input in the example, the key is preserved,
and the value becomes an object with two properties: the original value and
the result of multiplying the original value by a constant, a var
that is
defined as a directive in the header of the DataWeave script.
Important:
When you use a parameter to populate one of the keys of your output, you must
either enclose the parameter in parentheses (for example, (key)
), or
you need to prepend it with a $
and enclose it in quotation marks (for
example, '$key'
, as shown above). Otherwise, the name of the property is
treated as a literal string.
If you do not name the parameters, you need to reference them through
placeholders: $
for the value, $$
for the key, and $$$
for the index,
for example:
%dw 2.0 output application/xml --- { 'price' : 9 } mapObject('$$' : $)
<?xml version='1.0' encoding='UTF-8'?> <price>9</price>
The next example incorporates each index of the price input above, as well as the input keys and values.
%dw 2.0 output application/json --- priceList: payload.prices mapObject( ($$) : { '$$$' : $ } )
Notice that the index is surrounded in quotes ('$$$'
) because this Numeric
key must be coerced to a String and cannot be a Number. Alternatively, you
could write '$$$'
as ($$$ as String)
.
When the preceding script receives the price input above, it produces the following output:
{ 'priceList': { 'basic': { '0': '9.99' }, 'premium': { '1': '53' }, 'vip': { '2': '398.99' } } }
The next example returns the same output as the first mapObject
example above, which explicitly invokes the named parameters
(value, key, index)
.
%dw 2.0 output application/json var conversionRate=13 --- priceList: payload.prices mapObject( ($$): { dollars: $, localCurrency: $ * conversionRate, index_plus_1: $$$ + 1 } )
When you use a parameter to populate one of the keys of your output,
as with the case of $$
, you must either enclose it in quote marks
(for example, '$$'
) or parentheses (for example, ($$)
). Both
are equally valid.
mapObject(Null, (Any, Any, Number) → Any): Null
Helper function that allows mapObject
to work with null values.
1.1.29. match
match(String, Regex): Array<String>
Matches a string against a regular expression and returns an array that contains the entire matching expression, followed by all of the capture groups that match the provided regex.
It can be applied to the result of any evaluated expression and can return any evaluated expression. See Pattern Matching in DataWeave.
1
2
3
4
%dw 2.0
output application/json
---
hello: "anniepoint@mulesoft.com" match(/([a-z]*)@([a-z]*).com/)
1
2
3
4
5
6
7
{
"hello": [
"anniepoint@mulesoft.com",
"anniepoint",
"mulesoft"
]
}
In the example above, the regular expression describes an email address. It
contains two capture groups, what is before and what is after the @
. The
result is an array of three elements: the first is the whole email address,
the second matches one of the capture groups, the third matches the other one.
1.1.30. matches
matches(String, Regex): Boolean
Matches a string against a regular expression and returns true
or false
.
1
2
3
4
%dw 2.0
output application/json
---
b: "admin123" matches /(\d+)/
1
2
3
{
"b": false
}
For use cases where you need to output or conditionally process the matched value, see Pattern Matching in DataWeave.
1.1.31. max
max(Array<T>): T | Null
Returns the highest element in an array. Returns null when the array is empty
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: max([1, 1000]),
b: max([1, 2, 3]),
d: max([1.5, 2.5, 3.5])
}
1
2
3
4
5
{
"a": 1000,
"b": 3,
"d": 3.5
}
1.1.32. maxBy
maxBy(Array<T>, (item: T) → Comparable): T | Null
Returns the element used to get the maximum result using a function. Return null when array is empty.
1
2
3
4
%dw 2.0
output application/json
---
[ { a: "1" }, { a: "2" }, { a: "3" } ] maxBy ((item) -> item.a as Number)
1
{ "a": "3" }
1.1.33. min
min(Array<T>): T | Null
Returns the lowest element in an array. Returns null when the array is empty
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: min([1, 1000]),
b: min([1, 2, 3]),
d: min([1.5, 2.5, 3.5])
}
1
2
3
4
5
{
"a": 1,
"b": 1,
"d": 1.5
}
1.1.34. minBy
minBy(Array<T>, (item: T) → Comparable): T | Null
Returns the element used to get the minimum result using a function. Return null when array is empty
1
2
3
4
%dw 2.0
output application/json
---
[ { a: 1 }, { a: 2 }, { a: 3 } ] minBy (item) -> item.a
1
{ "a": 1 }
1.1.35. mod
mod(Number, Number): Number
Returns the remainder after performing a division of the first number by the second one.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: 3 mod 2,
b: 4 mod 2,
c: 2.2 mod 2
}
1
2
3
4
5
{
"a": 1,
"b": 0,
"c": 0.2
}
1.1.36. native
native(String): Nothing
Loads a native function using the specified identifier.
1.1.37. now
now(): DateTime
Returns a DateTime
object with the current date and time.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: now(),
b: now().day,
c: now().minutes
}
1
2
3
4
5
{
"a": "2015-12-04T18:15:04.091Z",
"b": 4,
"c": 15
}
See DataWeave Selectors for a list of possible selectors to use here.
1.1.38. orderBy
orderBy(O, (V, K) → R): O
Reorders the content of an array or object using a value returned by a
function. The function (a lambda) can be invoked with these parameters:
value
and index
.
If the parameters are not named, the index is defined by default as
$$
and the value as $
.
1
2
3
4
%dw 2.0
output application/json
---
orderByLetter: [{ letter: "d" }, { letter: "e" }, { letter: "c" }, { letter: "a" }, { letter: "b" }] orderBy($.letter)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"orderByLetter": [
{
"letter": "a"
},
{
"letter": "b"
},
{
"letter": "c"
},
{
"letter": "d"
},
{
"letter": "e"
}
]
}
Note that orderBy($.letter)
above produces the same result as orderBy($[0]).
The orderBy
function does not have an option to order in descending order
instead of ascending. In these cases, you can simply invert the order of
the resulting array using -
, for example:
1
2
3
4
%dw 2.0
output application/json
---
orderDescending: ([3,8,1] orderBy -$)
1
{ "orderDescending": [8,3,1] }
orderBy(Array<T>, (T, Number) → R): Array<T>
Sorts an array using the specified criteria.
1
2
3
4
%dw 2.0
output application/json
---
[3,2,3] orderBy $
1
2
3
4
5
[
2,
3,
3
]
1.1.39. pluck
pluck({ (K)?: V }, (V, K, Number) → R): Array<R>
Useful for mapping an object into an array, pluck
iterates over an input
object and returns an array consisting of keys, values, or indices of that
object. It is an alternative to mapObject
, which is similar but returns
an object, instead of an array.
The function can be invoked with any of these parameters: value
, key
,
index
. In the next example, 'pluck' iterates over each object within
'prices' and returns arrays of their keys, values, and indices.
If the parameters are not named, the value is defined by default as $
,
the key as $$
, and the index as $$$
.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
result: {
keys: payload.prices pluck($$),
values: payload.prices pluck($),
indices: payload.prices pluck($$$)
}
1
2
3
4
5
<prices>
<basic>9.99</basic>
<premium>53.00</premium>
<vip>398.99</vip>
</prices>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
'result': {
'keys': [
'basic',
'premium',
'vip'
],
'values': [
'9.99',
'53',
'398.99'
],
'indices': [
0,
1,
2
]
}
}
You can also use named keys and values as parameters. For example, the next
transformation example iterates over the prices
input
above and outputs an array with a single element.
1
2
3
4
%dw 2.0
output application/json
---
payload pluck(payload.prices)
1
2
3
4
5
6
7
[
{
'basic': '9.99',
'premium': '53.00',
'vip': '398.99'
}
]
Note that payload pluck(payload.prices)
produces the same result as
payload pluck(payload[0])
.
pluck(Null, (Nothing, Nothing, Nothing) → Any): Null
Helper function that allows pluck to work with null values.
1.1.40. pow
pow(Number, Number): Number
Returns the result of the first number a
to the power of the number
following the pow
operator.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: 2 pow 3,
b: 3 pow 2,
c: 7 pow 3
}
1
2
3
4
5
{
"a": 8,
"b": 9,
"c": 343
}
1.1.41. random
random(): Number
Returns a pseudo-random number greater than or equal to 0.0 and less than 1.0.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
price: random() * 1000
}
1.1.42. randomInt
randomInt(Number): Number
Returns a pseudo-random integer number between 0 and the specified number (exclusive).
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
price: randomInt(1000) //Returns an integer from 0 to 1000
}
1.1.43. read
read(String | Binary, String, Object)
Reads the input content (string or binary) with a mimeType reader for the data format of the input and returns the result of parsing that content.
The first argument provides the content to read. The second is its
format (or content type). The default content type is application/dw
.
A third, optional argument sets reader configuration properties.
For other formats and reader configuration properties, see Data Formats Supported by DataWeave.
1
2
3
4
%dw 2.0
output application/xml
---
read('{"name":"DataWeave"}', "application/json")
1
<name>DataWeave</name>
1.1.44. readUrl
readUrl(String, String, Object)
Same as the read
operator, but readURL
uses a URL as input. Otherwise, it
accepts the same arguments as read
.
The default input content type is application/dw
.
For other formats and reader configuration properties, see Data Formats Supported by DataWeave.
1
2
3
4
%dw 2.0
output application/xml
---
read('{"url":"https://www.mulesoft.com/"}')
1
2
<?xml version='1.0' encoding='UTF-8'?>
<url>https://www.mulesoft.com/</url>
1.1.45. reduce
reduce(Array<T>, (item: T, acumulator: T) → T): T | Null
Apply a reduction to the array using just two parameters: the accumulator
($$
), and the value ($
). By default, the accumulator starts at the first
value of the array. If the array is empty and no default value was set to the
accumulator then null value is returned.
1
2
3
4
%dw 2.0
output application/json
---
sum: [0, 1, 2, 3, 4, 5] reduce ($$ + $)
1
2
3
{
"sum": 15
}
1
2
3
4
%dw 2.0
output application/json
---
concat: ["a", "b", "c", "d"] reduce ($$ ++ $)
1
2
3
{
"concat": "abcd"
}
In some cases, you may not want to use the first element of the array as an accumulator. To set the accumulator to something else, you must define this in a lambda.
1
2
3
4
%dw 2.0
output application/json
---
concat: ["a", "b", "c", "d"] reduce ((val, acc = "z") -> acc ++ val)
1
2
3
{
"concat": "zabcd"
}
In other cases, you may want to turn an array into a string keeping the commas in between. The example below defines a lambda that also adds commas when concatenating.
1
2
3
4
%dw 2.0
output application/json
---
concat: ["a", "b", "c", "d"] reduce ((val, acc) -> acc ++ "," ++ val)
1
2
3
{
"concat": "a,b,c,d"
}
reduce(Array<T>, (item: T, acumulator: A) → A): A
1.1.46. replace
replace(String, Regex): ((Array<String>, Number) → String) → String
Replaces a section of a string for another, in accordance to a regular expression, and returns a modified string.
1
2
3
4
%dw 2.0
output application/json
---
b: 'admin123' replace /(\d+)/ with 'ID'
1
2
3
{
'b': 'adminID'
}
replace(String, String): ((Array<String>, Number) → String) → String
Replaces the occurrence of a given string inside other string with the specified value.
1
2
3
4
%dw 2.0
output application/json
---
b: "admin123" replace "123" with "ID"
1
2
3
{
"b": "adminID"
}
1.1.47. round
round(Number): Number
Rounds the value of a number to the nearest integer.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: round(1.2),
b: round(4.6),
c: round(3.5)
}
1
2
3
4
5
{
"a": 1,
"b": 5,
"c": 4
}
1.1.48. scan
scan(String, Regex): Array<Array<String>>
Returns an array with all of the matches in the given string. Each match is returned as an array that contains the complete match, as well as any capture groups there may be in your regular expression.
1
2
3
4
%dw 2.0
output application/json
---
hello: "anniepoint@mulesoft.com,max@mulesoft.com" scan /([a-z]*)@([a-z]*).com/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"hello": [
[
"anniepoint@mulesoft.com",
"anniepoint",
"mulesoft"
],
[
"max@mulesoft.com",
"max",
"mulesoft"
]
]
}
In the example above, we see that the search regular expression describes an email address. It contains two capture groups, what’s before and what’s after the @. The result is an array with two matches, as there are two email addresses in the input string. Each of these matches is an array of three elements, the first is the whole email address, the second matches one of the capture groups, the third matches the other one.
1.1.49. sizeOf
sizeOf(Array<Any>): Number
Returns the number of elements in an array (or anything that can be converted to an array, such as a string).
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
arraySize: sizeOf([1,2,3])
}
1
2
3
{
"arraySize": 3
}
sizeOf(Object): Number
Returns the number of elements in an object.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
objectSize: sizeOf({a:1,b:2})
}
1
2
3
{
"objectSize": 2
}
sizeOf(Binary): Number
Returns the byte length of a binary value.
sizeOf(String): Number
Returns the number of characters in an string.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
textSize: sizeOf("MuleSoft")
}
1
2
3
{
"textSize": 8
}
1.1.50. splitBy
splitBy(String, Regex): Array<String>
Splits a string into an array of separate elements. The function takes a
regular expression to identify some portion of that string, and if it finds
a match, uses the match as separator. splitBy
performs the opposite
operation of joinBy
.
Using the regular expression \^$.|?*+()-
, the following example finds the
the hyphen (-
) in the input string (a-b-c
), so it uses the hyphen as
a seperator.
1
2
3
4
%dw 2.0
output application/json
---
split: "a-b-c" splitBy(/\^$.|?*+()-/)
1
2
3
{
"split": ["a","b","c"]
}
splitBy(String, String): Array<String>
Splits a string into an array of separate elements. The function takes a
another string to look for some portion of the input string, and if it finds
a match, uses the match as separator. splitBy
performs the opposite
operation of joinBy
.
The following example uses the hyphen (-
) as the separator, but the
separator could be any other character in the input, such as splitBy("b")
.
1
2
3
4
%dw 2.0
output application/json
---
split: "a-b-c" splitBy("-")
1
2
3
{
"split": ["a", "b", "c"]
}
1.1.51. sqrt
sqrt(Number): Number
Returns the square root of the provided number.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: sqrt(4),
b: sqrt(25),
c: sqrt(100)
}
1
2
3
4
5
{
"a": 2.0,
"b": 5.0,
"c": 10.0
}
1.1.52. startsWith
startsWith(String, String): Boolean
Returns true
or false
depending on whether a string starts with a provided
substring.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
a: "Mariano" startsWith "Mar",
b: "Mariano" startsWith "Em"
}
1
2
3
4
{
"a": true,
"b": false
}
1.1.53. sum
sum(Array<Number>): Number
Given an array of numbers, it returns the result of adding of all of them.
1
2
3
4
%dw 2.0
output application/json
---
sum([1, 2, 3])
1
6
1.1.54. to
to(Number, Number): Range
Returns a range within the specified boundaries. The upper boundary is inclusive.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
"myRange": 1 to 10
}
1
2
3
{
"myRange": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
1.1.55. trim
trim(String): String
Removes any excess spaces at the start and end of a string.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
"a": trim(" my long text ")
}
1
2
3
{
"a": "my long text"
}
1.1.56. typeOf
typeOf(T): Type<T>
Returns the type of a value.
1
2
3
4
%dw 2.0
output application/json
---
typeOf("A Text")
1
"String"
1.1.57. unzip
unzip(Array<Array<T>>): Array<Array<T>>
Performs the opposite function of [zip arrays]. That is, given a single array where each index contains an array with two elements, it outputs two separate arrays, each with the corresponding elements of each pair.
This can also be scaled up: If the indexes in the provided array contain arrays with more than two elements, the output will contain as many arrays as there are elements for each index.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: unzip([[0,"a"],[1,"b"],[2,"c"],[3,"d"]]),
b: unzip([ [0,"a"], [1,"a"], [2,"a"], [3,"a"]]),
c: unzip([ [0,"a"], [1,"a","foo"], [2], [3,"a"]])
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"a":[
[0, 1, 2, 3],
["a", "b", "c", "d"]
],
"b": [
[0,1,2,3],
["a","a","a","a"]
],
"c": [
[0,1,2,3]
]
}
Note that even though example b
can be considered the inverse function of
example b
in [zip array], the result is not analogous because it returns
an array of repeated elements instead of a single element. Also note that in
example c
, the number of elements in each component of the original array
is not consistent. So the output only creates as many full arrays as it can,
in this case just one.
1.1.58. upper
upper(String): String
Returns the provided string in uppercase characters.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
name: upper("mulesoft")
}
1
2
3
{
"name": "MULESOFT"
}
1.1.59. uuid
uuid(): String
Returns a v4 UUID using random numbers as the source.
%dw 2.0 output application/json --- uuid()
"4a185c3b-05b3-4554-b72e-d5c07524cf91"
1.1.60. with
with(((V, U) → R) → X, (V, U) → R): X
When used with replace
, with
applies the specified function.
1
2
3
4
%dw 2.0
output application/json
---
ssn: "987-65-4321" replace /[0-9]/ with("x")
1
{ ssn: "xxx-xx-xxxx" }
1.1.61. write
write(Any, String, Object): Any
Writes input content to a specific format. Specifically, the write
function
returns a string with the serialized representation of the value in the
specified mimeType (format).
The first argument points to the input to write. The second is the format
in which to write it. The default is application/dw
. A third, optional
argument lists writer configuration properties.
See Data Formats Supported by DataWeave for a full list of configuration properties for each format-specific writer.
1
2
3
4
5
6
%dw 2.0
output application/xml
---
{
"output" : write(payload, "application/csv", {"separator" : "|"})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
{
"Name": "Mr White",
"Email": "white@mulesoft.com",
"Id": "1234",
"Title": "Chief Java Prophet"
},
{
"Name": "Mr Orange",
"Email": "orange@mulesoft.com",
"Id": "4567",
"Title": "Integration Ninja"
}
]
1
2
3
4
5
<?xml version='1.0' encoding='US-ASCII'?>
<output>Name|Email|Id|Title
Mr White|white@mulesoft.com|1234|Chief Java Prophet
Mr Orange|orange@mulesoft.com|4567|Integration Ninja
</output>
1.1.62. zip
zip(Array<T>, Array<R>): Array<Array<T | R>>
Given two or more separate lists, the zip function can be used to merge them together into a single list of consecutive n-tuples. Imagine two input lists each being one side of a zipper: similar to the interlocking teeth of a zipper, the zip function interdigitates each element from each input list, one element at a time.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
a: [0, 1, 2, 3] zip ['a', 'b', 'c', 'd'],
b: [0, 1, 2, 3] zip ['a'],
c: [0, 1, 2, 3] zip ['a', 'b']
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
'a': [
[0,'a'],
[1,'b'],
[2,'c'],
[3,'d']
],
'b': [
[0,'a']
],
'c': [
[0,'a'],
[1,'b']
]
}
Here is another example of the zip function with more than two input lists.
1
2
3
4
%dw 2.0
output application/json
---
payload.list1 zip payload.list2 zip payload.list3
1
2
3
4
5
6
{
'list1': ['a', 'b', 'c', 'd'],
'list2': [1, 2, 3],
'list3': ['aa', 'bb', 'cc', 'dd'],
'list4': [['a', 'b', 'c'], [1, 2, 3, 4], ['aa', 'bb', 'cc', 'dd']]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[
[
'a',
1,
'aa'
],
[
'b',
2,
'bb'
],
[
'c',
3,
'cc'
]
]
1.2. Types
1.2.1. Any
Any
type, is the top level type. Any extends all of the system types.
That means anything can be assigned to a Any
typed variable.
1
Any
1.2.2. Array
Array
type, requires a Type(T) to represent the elements of the list.
Example: Array<Number> represents an array of numbers.
1
Array
1.2.3. Binary
A Blob
1
Binary
1.2.4. Boolean
A Boolean
type true
of false
1
Boolean
1.2.5. CData
XML defines a custom type named CData that extends from String and is used to identify a CDATA XML block.
It can be used to tell the writer to wrap the content inside CDATA or to
check if the input string arrives inside a CDATA block. :cdata
inherits
from the type :string
.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/xml
---
{
users:
{
user : "Mariano" as CData,
age : 31 as CData
}
}
1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user><![CDATA[Mariano]]></user>
<age><![CDATA[31]]></age>
</users>
1
String {cdata: true}
1.2.6. Comparable
A union type that represents all the types that can be compared to each other.
1
String | Number | Boolean | DateTime | LocalDateTime | Date | LocalTime | Time | TimeZone
1.2.7. Date
A Date represented by Year Month Day
1
Date
1.2.8. DateTime
A Date Time with in a TimeZone
1
DateTime
1.2.9. Dictionary
Generic Dictionary interface
1
{ _?: T }
1.2.10. Enum
This type is based in the Enum Java class.
It must always be used with the class
property, specifying the full Java
class name of the class, as shown in the example below.
1
2
3
4
%dw 2.0
output application/java
---
"Male" as Enum {class: "com.acme.GenderEnum"}
1
String {enumeration: true}
1.2.11. Iterator
This type is based in the iterator Java class. The iterator contains a collection, and includes methods to iterate through and filter it.
Just like the Java class, the iterator is designed to be consumed only once. For example, if you then pass this value to a Logger component would result in consuming it and it would no longer be readable to further elements in the flow. |
1
Array {iterator: true}
1.2.12. Key
A Key of an Object
1
Key
1.2.13. LocalDateTime
A DateTime in the current TimeZone
1
LocalDateTime
1.2.14. LocalTime
A Time in the current TimeZone
1
LocalTime
1.2.15. Namespace
A namespace type represented by an URI and a Prefix
1
Namespace
1.2.16. Nothing
Bottom type. This type is can be assigned to all the types
1
Nothing
1.2.17. Null
A null type
1
Null
1.2.18. Number
A number any number decimals and integers are represented by Number
type
1
Number
1.2.19. Object
Object
type. Represents any object, collection of Key Value Pairs
1
Object
1.2.20. Period
A Period
1
Period
1.2.21. Range
A Range type represents a sequence of numbers
1
Range
1.2.22. Regex
Regex Type
1
Regex
1.2.23. SimpleType
A union type that represents all the simple types.
1
String | Boolean | Number | DateTime | LocalDateTime | Date | LocalTime | Time | TimeZone | Period
1.2.24. String
These are the native types of DataWeave.
They are the only types that allow the ???
definition.
1
String
1.2.25. Time
A Time in a specific TimeZone
1
Time
1.2.26. TimeZone
A TimeZone
1
TimeZone
1.2.27. Type
Represents a Type in the DataWeave Type System
1
Type
1.2.28. Uri
An Uri
1
Uri
2. dw::Crypto
The functions described here are packaged in the Crypto module. The module is included with Mule runtime, but you must import it to your DataWeave code by adding the line `import dw::Crypto` to your header.
Example [source,DataWeave, linenums] ---- %dw 2.0 import dw::Crypto --- Crypto::MD5("asd" as Binary) ----
This module contains encrypting functions that follow common algorithms such as MD5, SHA1, etc.
2.1. Functions
2.1.1. HMACBinary
HMACBinary(Binary, Binary): Binary
Computes a Hash-based Message Authentication Code (HMAC) using the SHA1 hash function.
%dw 2.0 import dw::Crypto output application/json --- { "HMAC": Crypto::HMACBinary(("aa" as Binary), ("aa" as Binary)) }
{ "HMAC": "\u0007\ufffd\ufffd\ufffd]\ufffd\ufffd\u0006\ufffd\u0006\ufffdsv:\ufffd\u000b\u0016\ufffd\ufffd\ufffd" }
2.1.2. HMACWith
HMACWith(Binary, Binary): String
Computes the HMAC hash and transforms and transforms the binary result into a hexadecimal lower case string.
2.1.3. MD5
MD5(Binary): String
Computes the MD5 hash and transforms the binary result into a hexadecimal lower case string.
%dw 2.0 import dw::Crypto output application/json --- Crypto::MD5("asd" as Binary)
"7815696ecbf1c96e6894b779456d330e"
2.1.4. SHA1
SHA1(Binary): String
Computes the SHA1 hash and transforms and transforms the binary result into a hexadecimal lower case string.
%dw 2.0 import dw::Crypto output application/json --- Crypto::SHA1("dsasd" as Binary)
"2fa183839c954e6366c206367c9be5864e4f4a65"
2.1.5. hashWith
hashWith(Binary, String): Binary
Computes the hash of the specified content with the given algorithm name and returns the binary content.
Algorithm name can be
Name | Description |
---|---|
MD2 |
The MD2 message digest algorithm as defined in RFC 1319[http://www.ietf.org/rfc/rfc1319.txt]. |
MD5 |
The MD5 message digest algorithm as defined in RFC 1321[http://www.ietf.org/rfc/rfc1321.txt]. |
SHA-1 SHA-256 SHA-384 SHA-512 |
Hash algorithms defined in the FIPS PUB 180-2 [http://csrc.nist.gov/publications/fips/index.html]. SHA-256 is a 256-bit hash function intended to provide 128 bits of security against collision attacks, while SHA-512 is a 512-bit hash function intended to provide 256 bits of security. A 384-bit hash may be obtained by truncating the SHA-512 output. |
3. dw::Runtime
The functions described here are packaged in the Runtime module. The module is included with Mule Runtime, but you must import it to your DataWeave code by adding the line import dw::Runtime
to your header.
This module contains functions that allow you to interact with the DataWeave engine.
3.1. Functions
3.1.1. fail
fail(String): Nothing
Throws an exception with the specified message.
1
2
3
4
%dw 2.0
import dw::Runtime
---
Runtime::fail("Error")
Error
3.1.2. failIf
failIf(T, (value: T) → Boolean, String): T
Throws an exception with the specified message if the expression in the evaluator returns true
. If not, return the value.
1
2
3
4
5
%dw 2.0
import failIf from dw::Runtime
output application/json
---
{ "a" : "b" } failIf ("b" is String)
Failed
3.1.3. locationString
locationString(Any): String
Returns the location string of a given value
3.1.4. prop
prop(String): String | Null
Returns the value of the property with the specified name or null if not defined
3.1.5. props
props(): Dictionary<String>
Returns all the properties configured for the underlying runtime
3.1.6. try
try(() → T): TryResult<T>
Evaluates the delegate (a lambda without inputs) and returns an object with the result or an error message.
1
2
3
4
5
%dw 2.0
import try, fail from dw::Runtime
output application/json
---
try(fail)
{ "success": false, "error": { "kind": "UserException", "message": "Error", "location": "Unknown location", "stack": [ ] } }
3.1.7. wait
wait(T, Number): T
Stops the execution for the specified timeout (in milliseconds).
1
2
3
4
5
%dw 2.0
import * from dw::Runtime
output application/json
---
{user: 1} wait 2000
{ "user": 1 }
3.2. Types
3.2.1. TryResult
Object with a result or error message. If success
is false
, it contains the error
. If true
, it provides the result
.
1
{ success: Boolean, result?: T, error?: { kind: String, message: String, stack?: Array<String>, location?: String } }
4. dw::System
The functions described here are packaged in the System module. The module is included with the Mule runtime, but you must import it to your DataWeave code by adding the line import dw::System
to your header.
1
2
3
4
%dw 2.0
import dw::System
---
System::envVar("SYS_PSWD")
This module contains functions that allow you to interact with the underlying system.
4.1. Functions
4.1.1. envVar
envVar(String): String | Null
Returns an environment variable with the specified name, or null
if it’s not defined.
1
2
3
4
5
%dw 2.0
import dw::System
output application/json
---
System::envVar("SYS_PSWD")
4.1.2. envVars
envVars(): Dictionary<String>
Returns all of the environment variables defined in the hosted System.
1
2
3
4
5
%dw 2.0
import dw::System
output application/json
---
System::envVars().SYS_PSWD
5. dw::core::Arrays
5.1. Functions
5.1.1. countBy
countBy(Array<T>, (T) → Boolean): Number
Counts the matching elements using a matchingFunction(T)
1
2
3
4
%dw 2.0
output application/json
---
[1, 2, 3] countBy (($ mod 2) == 0)
1
1
5.1.2. divideBy
divideBy(Array<T>, Number): Array<Array<T>>
Divides an Array of items into sub arrays. .Transform
1
2
3
output application/json
---
[1, 2, 3, 4, 5] divideBy 2
1
2
3
4
5
6
7
8
9
10
[
[
1,
2
],
[
4,
5
]
]
5.1.3. every
every(Array<T>, (T) → Boolean): Boolean
Returns true if every element of the list matches the condition. It stops the iterations after the first negative evaluation. .Transform
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
%dw 2.0
import * from dw::core::Arrays
var arr0: Array<Number> = []
output application/json
---
{
ok: [
[1,2,3] some (($ mod 2) == 0),
[1,2,3] some (($ mod 2) == 1),
[1,2,3,4,5,6,7,8] some (log('should stop at 2 ==', $) == 2),
[1,2,3] some ($ == 1),
[1,1,1] every ($ == 1),
[1,1,1] some ($ == 1),
[1] every ($ == 1),
[1] some ($ == 1),
],
err: [
[1,2,3] every ((log('should stop at 2 ==', $) mod 2) == 1),
[1,2,3] some ($ == 100),
[1,1,0] every ($ == 1),
[0,1,1,0] every (log('should stop at 0 ==', $) == 1),
[1] some ($ == 2),
[1,2,3] every ($ == 1),
arr0 every true,
arr0 some true,
arr0 some ($ is Number)
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"ok": [
true,
true,
true,
true,
true,
true,
true,
true
],
"err": [
false,
false,
false,
false,
false,
false,
false,
false,
false
]
}
5.1.4. some
some(Array<T>, (T) → Boolean): Boolean
Returns true if some element of the list matches the condition. It stops the iterations after the first match.
For an example, see every
.
5.1.5. sumBy
sumBy(Array<T>, (T) → Number): Number
Adds the values returned by the right hand side function
1
2
3
4
5
%dw 2.0
output application/json
---
sumBy([ { a: 1 }, { a: 2 }, { a: 3 } ], (item) -> item.a)
// same as [ { a: 1 }, { a: 2 }, { a: 3 } ] sumBy $.a
1
6
6. dw::core::Binaries
6.1. Functions
6.1.1. fromBase64
fromBase64(String): Binary
Converts a base64 string representation into a binary
For an example, see toBase64
.
6.1.2. fromHex
fromHex(String): Binary
Converts an hexadecimal string representation into a binary
1
2
3
4
5
%dw 2.0
import * from dw::core::Binaries
output application/json
---
{ "binary": fromHex('4D756C65')}
{ "binary": "Mule" }
6.1.3. toBase64
toBase64(Binary): String
Transforms the specified binary into the base64 string representation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
%dw 2.0
import * from dw::core::Binaries
output application/json
---
toBase64(fromBase64(12463730))
----
.Output
----
12463730
----
=== toHex
==== toHex(Binary): String
Converts the specified binary into the hexadecimal String representation
.Transform
[source,DataWeave, linenums]
%dw 2.0 import * from dw::core::Binaries output application/json --- { "hex" : toHex('Mule') }
.Output
{ "hex": "4D756C65" }
= dw::core::Objects == Functions === divideBy ==== divideBy(Object, Number): Array<Object> Divides the object into sub-objects with the specified number of properties. .Transform [source,DataWeave, linenums]
%dw 2.0 import divideBy from dw::core::Objects --- {a: 123,b: true, a:123, b:false} divideBy 2
.Output [source,JSON, linenums]
[ { "a": 123, "b": true }, { "a": 123, "b": false } ]
=== entrySet ==== entrySet(T) Returns a list of key-value pair objects that describe the object entries. .Transform [source,DataWeave, linenums]
%dw 2.0 import dw::core::Objects --- Objects::entrySet({a: true, b: 1})
.Output [source,JSON, linenums]
[ { key: "a", value: true, attributes: null }, { key: "b", value: 1, attributes: null } ]
=== keySet ==== keySet(T): ? Returns the list of key names from an object. .Transform [source,DataWeave, linenums]
%dw 2.0 import dw::core::Objects --- Objects::keySet({a: true, b: 1})
.Output [source,JSON, linenums]
["a","b"]
=== mergeWith ==== mergeWith(T, V): ? Keeps the target object intact, then appends to the target object any key-value pairs from the source where the key is not already in the target. .Transform [source,DataWeave, linenums]
%dw 2.0 import mergeWith from dw::core::Objects --- {a: true, b: 1} mergeWith {a: false, c: "Test"}
.Output [source,JSON, linenums]
{"a": false, "b": 1 , "c": "Test"}
==== mergeWith(Null, T): T Helper method to make `mergeWith` null friendly. ==== mergeWith(T, Null): T Helper method to make `mergeWith` null friendly. === nameSet ==== nameSet(Object): Array<String> Returns the list of key names from an object. .Transform [source,DataWeave, linenums]
%dw 2.0 import dw::core::Objects --- Objects::nameSet({a: true, b: 1})
.Output [source,JSON, linenums]
["a","b"]
=== valueSet ==== valueSet({ (K)?: V }): Array<V> Returns the list of key values of an object. .Transform [source,DataWeave, linenums]
%dw 2.0 import dw::core::Objects --- Objects::valueSet({a: true, b: 1})
.Output [source,JSON, linenums]
[true,1]
= dw::core::Strings The functions described here are packaged in the Strings module. The module is included with the Mule runtime, but you must import it to your DataWeave code by adding the line `import dw::core::Strings` to your header. Example [source,DataWeave, linenums]
%dw 2.0 import dw::core::Strings --- Strings::pluralize("box")
== Functions === camelize ==== camelize(String): String Returns the provided string in camel case. .Transform [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::Strings output application/json --- { a: camelize("customer"), b: camelize("customer_first_name"), c: camelize("customer name") }
.Output [source,json,linenums]
{ "a": "customer", "b": "customerFirstName", "c": "customer name" }
=== capitalize ==== capitalize(String): String Returns the provided string with every word starting with a capital letter and no underscores. It also replaces underscores with spaces and puts a space before each capitalized word. .Transform [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::Strings output application/json --- { a: capitalize("customer"), b: capitalize("customer_first_name"), c: capitalize("customer NAME"), d: capitalize("customerName") }
.Output [source,json,linenums]
{ "a": "Customer", "b": "Customer First Name", "c": "Customer Name", "d": "Customer Name" }
=== charCode ==== charCode(String): Number Returns a Number, representing the unicode of the first character of the specified String. This functions fails if the String is empty .Transform [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::Strings output application/json --- { a: charCode("b") }
.Output [source,json,linenums]
{ "a": 98 }
=== charCodeAt ==== charCodeAt(String, Number): Number Returns a Number, representing the unicode of the character at the specified index. This functions if the index is invalid .Transform [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::Strings output application/json --- { a: charCodeAt("baby", 2) }
.Output [source,json,linenums]
{ "a": 98 }
=== dasherize ==== dasherize(String): String Returns the provided string with every word separated by a dash. .Transform [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::Strings output application/json --- { a: dasherize("customer"), b: dasherize("customer_first_name"), c: dasherize("customer NAME") }
.Output [source,json,linenums]
{ "a": "customer", "b": "customer-first-name", "c": "customer-name" }
=== fromCharCode ==== fromCharCode(Number): String Returns the String of the specified Number code. === ordinalize ==== ordinalize(Number): String Returns the provided numbers set as ordinals. .Transform [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::Strings output application/json --- { a: ordinalize(1), b: ordinalize(8), c: ordinalize(103) }
.Output [source,json,linenums]
{ "a": "1st", "b": "8th", "c": "103rd" }
=== pluralize ==== pluralize(String): String Returns the provided string transformed into its plural form. .Transform [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::Strings output application/json --- { a: pluralize("box"), b: pluralize("wife"), c: pluralize("foot") }
.Output [source,json,linenums]
{ "a": "boxes", "b": "wives", "c": "feet" }
=== singularize ==== singularize(String): String Returns the provided string transformed into its singular form. .Transform [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::Strings output application/json --- { a: singularize("boxes"), b: singularize("wives"), c: singularize("feet") }
.Output [source,json,linenums]
{ "a": "box", "b": "wife", "c": "foot" }
=== underscore ==== underscore(String): String Returns the provided string with every word separated by an underscore. .Transform [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::Strings output application/json --- { a: underscore("customer"), b: underscore("customer-first-name"), c: underscore("customer NAME") }
.Output [source,json,linenums]
{ "a": "customer", "b": "customer_first_name", "c": "customer_NAME" }
= dw::core::URL == Functions === compose ==== compose(Array<String>, Array<String>): String Compose is a custom interpolator used to replace URL components by the encodeURIComponent result of it. .Transform [source,DataWeave, linenums]
%dw 2.0
import * from dw::core::URL
output application/json
---
{ 'composition': compose encoding http://asd/$(' text to encode ')/text now
}
.Output [source,JSON, linenums]
{ "composition": "encoding http://asd/%20text%20to%20encode%20/text now" }
6.1.4. decodeURI
decodeURI(String): String
The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by encodeURI or by a similar routine.
Replaces each escape sequence in the encoded URI with the character that it represents,
but does not decode escape sequences that could not have been introduced by encodeURI.
The character #
is not decoded from escape sequences.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::URL
output application/json
---
{
a: decodeURI('http://asd/%20text%20to%20decode%20/text')
}
1
2
3
{
"a": "http://asd/ text to decode /text"
}
6.1.5. decodeURIComponent
decodeURIComponent(String): String
The decodeURIComponent() function decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine.
For an example, see encodeURIComponent
.
6.1.6. encodeURI
encodeURI(String): String
The encodeURI() function encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
Assumes that the URI is a complete URI, so does not encode reserved characters that have special meaning in the URI.
encodeURI replaces all characters except the following with the appropriate UTF-8 escape sequences:
Type | Includes |
---|---|
Reserved characters |
; , / ? : @ & = $ |
Unescaped characters |
alphabetic, decimal digits, - _ . ! ~ * ' ( ) |
Number sign |
# |
6.1.7. encodeURIComponent
encodeURIComponent(String): String
The encodeURIComponent() function encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( ) encodeURIComponent differs from encodeURI in that it encodes reserved characters and the Number sign # of encodeURI:
Type | Includes |
---|---|
Reserved characters |
|
Unescaped characters |
alphabetic, decimal digits, - _ . ! ~ * ' ( ) |
Number sign |
[source,DataWeave, linenums]
%dw 2.0 import * from dw::core::URL output application/json --- { "comparing_encode_functions_output" : { "encodeURIComponent" : encodeURI(" PATH/ TO /ENCODE "), "encodeURI" : encodeURI(" PATH/ TO /ENCODE "), "encodeURIComponent_to_hex" : encodeURIComponent(";,/?:@&="), "encodeURI_not_to_hex" : encodeURI(";,/?:@&="), "encodeURIComponent_not_encoded" : encodeURIComponent("-_.!~*'()"), "encodeURI_not_encoded" : encodeURI("-_.!~*'()") }, "comparing_decode_function_output": { "decodeURIComponent" : decodeURIComponent("%20PATH/%20TO%20/DECODE%20"), "decodeURI" : decodeURI("%20PATH/%20TO%20/DECODE%20"), "decodeURIComponent_from_hex" : decodeURIComponent("%3B%2C%2F%3F%3A%40%26%3D"), "decodeURI_from_hex" : decodeURI("%3B%2C%2F%3F%3A%40%26%3D"), "decodeURIComponent_from_hex" : decodeURIComponent("%2D%5F%2E%21%7E%2A%27%28%29%24"), "decodeURI_from_hex" : decodeURI("%2D%5F%2E%21%7E%2A%27%28%29%24") } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"comparing_encode_functions_output": {
"encodeURIComponent": "%20PATH/%20TO%20/ENCODE%20",
"encodeURI": "%20PATH/%20TO%20/ENCODE%20",
"encodeURIComponent_to_hex": "%3B%2C%2F%3F%3A%40%26%3D",
"encodeURI_not_to_hex": ";,/?:@&=",
"encodeURIComponent_not_encoded": "-_.!~*'()",
"encodeURI_not_encoded": "-_.!~*'()"
},
"comparing_decode_function_output": {
"decodeURIComponent": " PATH/ TO /DECODE ",
"decodeURI": " PATH/ TO /DECODE ",
"decodeURIComponent_from_hex": ";,/?:@&=",
"decodeURI_from_hex": ";,/?:@&=",
"decodeURIComponent_from_hex": "-_.!~*'()$",
"decodeURI_from_hex": "-_.!~*'()$"
}
}
6.1.8. parseURI
parseURI(String): URI
Parses an URL and returns an URI object.
The isValid: Boolean
property dennotes if the parse was succeed.
Every field in the URI object is optional, and it will be present only if it was present in the original URL
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::URL
output application/json
---
{
'composition': parseURI('https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#footer')
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
"composition": {
"isValid": true,
"raw": "https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#footer",
"host": "en.wikipedia.org",
"authority": "en.wikipedia.org",
"fragment": "footer",
"path": "/wiki/Uniform_Resource_Identifier",
"scheme": "https",
"isAbsolute": true,
"isOpaque": false
}
}
== Types
=== URI
.Definition
[source,DataWeave,linenums]
{ isValid: Boolean, host?: String, authority?: String, fragment?: String, path?: String, port?: Number, query?: String, scheme?: String, user?: String, isAbsolute?: Boolean, isOpaque?: Boolean }
= dw::util::Diff This utility module returns calculates the difference between two values and returns the list of differences == Functions === diff ==== diff(Any, Any, { unordered?: Boolean }, String): Diff Returns the structural diference between two values. It returns an Difference. When comparing objects it can be either ordered or unordered. By default is ordered this means that two object are not going to have a difference if their key value pairs are in the same order. To change this behaviour specify the diffConfig parameter with {unordered: true} .Example: [source,DataWeave,linenums]
%dw 2.0 import * from dw::util::Diff output application/json var a = { age: "Test" } var b = { age: "Test2" } --- a diff b
.Output: [source,xml,linenums]
{ "matches": false, "diffs": [ { "expected": "\"Test2\"", "actual": "\"Test\"", "path": "(root).age" } ] }
== Types === Diff Describes the entire difference beteween two values .Definition [source,DataWeave,linenums]
{ matches: Boolean, diffs: Array<Difference> }
=== Difference Describes a single difference between two values at a given structure .Definition [source,DataWeave,linenums]
{ expected: String, actual: String, path: String }
= dw::util::Timer == Functions === currentMilliseconds ==== currentMilliseconds(): Number Returns the current time in milliseconds === duration ==== duration(() -> T): DurationMeasurement<T> Executes the function and returns an object with the taken time in milliseconds with the result of the function === time ==== time(() -> T): TimeMeasurement<T> Executes the specified function and returns an object with the start time and end time with the result of the function === toMilliseconds ==== toMilliseconds(DateTime): Number Returns the representation of the specified DateTime in milliseconds == Types === DurationMeasurement Represents a time taken by a function call .Definition [source,DataWeave,linenums]
{ time: Number, result: T }
=== TimeMeasurement Represents a start/end time meassurement .Definition [source,DataWeave,linenums]
{ start: DateTime, result: T, end: DateTime }
:leveloffset: 0