1. dw::Core
This module contains core DataWeave functions for data transformations. It is automatically imported into any DataWeave script. For documentation on DataWeave 1.0 functions, see DataWeave Operators.
1.1. Functions
1.1.1. ++
++(Array<S>, Array<T>): Array<S | T>
Concatenates two values.
This version of ++
concatenates the elements of two arrays into a
new array. Other versions act on strings, objects, and the various date and
time formats that DataWeave supports.
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. Also
note that the arrays can contain any supported data type.
Parameters
Name | Description |
---|---|
|
The source array. |
|
The array to concatenate with the source array. |
Example
The example concatenates an Array<Number>
with an Array<String>
. Notice
that it outputs the result as the value of a JSON object.
1
2
3
4
%dw 2.0
output application/json
---
{ "result" : [0, 1, 2] ++ ["a", "b", "c"] }
1
{ "result": [0, 1, 2, "a", "b", "c"] }
Example
1
2
3
4
%dw 2.0
output application/json
---
{ "a" : [0, 1, true, "my string"] ++ [2, [3,4,5], {"a": 6}] }
1
{ "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.
Parameters
Name | Description |
---|---|
|
The source string. |
|
The string to concatenate with the source string. |
Example
This example concatenates two strings. Here, Mule
is treated as
Array<String> ["M", "u", "l", "e"]
. Notice that the example outputs the
result MuleSoft
as the value of a JSON object.
1
2
3
4
%dw 2.0
output application/json
---
{ "name" : "Mule" ++ "Soft" }
1
{ "name": "MuleSoft" }
++(T, Q): T & Q
Concatenates two 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.
Parameters
Name | Description |
---|---|
|
The source object. |
|
The object to concatenate with the source object. |
Example
This example concatenates two objects and transforms them to XML. Notice that
it flattens the array of objects {aa: "a", bb: "b"}
into separate XML
elements and that the output uses the keys of the specified JSON objects as
XML elements and the values of those objects as XML values.
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>
++(Date, LocalTime): LocalDateTime
Appends a LocalTime
with a Date
to return a 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. Note that the order in which the two objects are
concatenated is irrelevant, so logically, Date LocalTime` produces the
same result as `LocalTime Date
.
Parameters
Name | Description |
---|---|
|
A |
|
A |
Example
This example concatenates a Date
and LocalTime
object to return a
LocalDateTime
.
1
2
3
4
%dw 2.0
output application/json
---
{ "LocalDateTime" : (|2017-10-01| ++ |23:57:59|) }
1
{ "LocalDateTime": "2017-10-01T23:57:59" }
++(LocalTime, Date): LocalDateTime
Appends a LocalTime
with a Date
to return a LocalDateTime
.
Note that the order in which the two objects are concatenated is irrelevant,
so logically, LocalTime Date` produces the same result as
`Date LocalTime
.
Parameters
Name | Description |
---|---|
|
A |
|
A |
Example
This example concatenates LocalTime
and Date
objects to return a
LocalDateTime
.
1
2
3
4
%dw 2.0
output application/json
---
{ "LocalDateTime" : (|23:57:59| ++ |2003-10-01|) }
1
{ "LocalDateTime": "2017-10-01T23:57:59" }
++(Date, Time): DateTime
Appends a Date
to a Time
in order to return a DateTime
.
Note that the order in which the two objects are concatenated is irrelevant,
so logically, Date
+ Time
produces the same result as Time
+ Date
.
Parameters
Name | Description |
---|---|
|
A |
|
A |
Example
This example concatenates Date
and Time
objects to return a DateTime
.
1
2
3
4
%dw 2.0
output application/json
---
[ |2017-10-01| ++ |23:57:59-03:00|, |2017-10-01| ++ |23:57:59Z| ]
1
[ "2017-10-01T23:57:59-03:00", "2017-10-01T23:57:59Z" ]
++(Time, Date): DateTime
Appends a Date
to a Time
object to return a DateTime
.
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
.
Parameters
Name | Description |
---|---|
|
A |
|
A |
Example
This example concatenates a Date
with a Time
to output a DateTime
.
Notice that the inputs are surrounded by pipes (|
).
1
2
3
4
%dw 2.0
output application/json
---
|2018-11-30| ++ |23:57:59+01:00|
1
"2018-11-30T23:57:59+01:00"
Example
This example concatenates Time
and Date
objects to return DateTime
objects. Note that the first LocalTime
object is coerced to a `Time
.
Notice that the order of the date and time inputs does not change the order
of the output DateTime
.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
"DateTime1" : (|23:57:59| as Time) ++ |2017-10-01|,
"DateTime2" : |23:57:59Z| ++ |2017-10-01|,
"DateTime3" : |2017-10-01| ++ |23:57:59+02:00|
}
1
2
3
4
5
{
"DateTime1": "2017-10-01T23:57:59Z",
"DateTime2": "2017-10-01T23:57:59Z",
"DateTime3": "2017-10-01T23:57:59+02:00"
}
++(Date, TimeZone): DateTime
Appends a TimeZone
to a Date
type value and returns a DateTime
result.
Parameters
Name | Description |
---|---|
|
A |
|
A |
Example
This example concatenates Date
and TimeZone
(-03:00
) to return a
DateTime
. Note the local time in the DateTime
is 00:00:00
(midnight).
1
2
3
4
%dw 2.0
output application/json
---
{ "DateTime" : (|2017-10-01| ++ |-03:00|) }
1
{ "DateTime": "2017-10-01T00:00:00-03:00" }
++(TimeZone, Date): DateTime
Appends a Date
to a TimeZone
in order to return a DateTime
.
Parameters
Name | Description |
---|---|
|
A |
|
A |
Example
This example concatenates TimeZone
(-03:00
) and Date
to return a
DateTime
. Note the local time in the DateTime
is 00:00:00
(midnight).
1
2
3
4
%dw 2.0
output application/json
---
{ "DateTime" : |-03:00| ++ |2017-10-01| }
1
{ "DateTime": "2017-10-01T00:00:00-03:00" }
++(LocalDateTime, TimeZone): DateTime
Appends a TimeZone
to a LocalDateTime
in order to return a DateTime
.
Parameters
Name | Description |
---|---|
|
A |
|
A |
Example
This example concatenates LocalDateTime
and TimeZone
(-03:00
) to return a
DateTime
.
1
2
3
4
%dw 2.0
output application/json
---
{ "DateTime" : (|2003-10-01T23:57:59| ++ |-03:00|) }
1
{ "DateTime": "2003-10-01T23:57:59-03:00 }
++(TimeZone, LocalDateTime): DateTime
Appends a LocalDateTime
to a TimeZone
in order to return a DateTime
.
Parameters
Name | Description |
---|---|
|
A |
|
A |
Example
This example concatenates TimeZone
(-03:00
) and LocalDateTime
to return
a DateTime
.
1
2
3
4
%dw 2.0
output application/json
---
{ "TimeZone" : (|-03:00| ++ |2003-10-01T23:57:59|) }
1
{ "TimeZone": "2003-10-01T23:57:59-03:00" }
++(LocalTime, TimeZone): Time
Appends a TimeZone
to a LocalTime
in order to return a Time
.
Parameters
Name | Description |
---|---|
|
A |
|
A |
Example
This example concatenates LocalTime
and TimeZone
(-03:00
) to return a
Time
. Note that the output returns`:00` for the unspecified seconds.
1
2
3
4
%dw 2.0
output application/json
---
{ "Time" : (|23:57| ++ |-03:00|) }
1
{ "Time": "23:57:00-03:00" }
++(TimeZone, LocalTime): Time
Appends a LocalTime
to a TimeZone
in order to return a Time
.
Parameters
Name | Description |
---|---|
|
A |
|
A |
Example
This example concatenates TimeZone
(-03:00
) and LocalTime
to return a
Time
. Note that the output returns`:00` for the unspecified seconds.
1
2
3
4
%dw 2.0
output application/json
---
{ "Time" : (|-03:00| ++ |23:57|) }
1
2
3
{
"Time": "23:57:00-03:00"
}
1.1.2. —
--(Array<S>, Array<Any>): Array<S>
Removes specified values from an input value.
This version of --
removes specified items from an array. Other
versions act on objects, strings, and the various date and time formats that
are supported by DataWeave.
Name |
Description |
|
The array containing items to remove. |
|
Items to remove from the list. |
Example
This example removes specified items from an array. Specifically, it removes
all instances of the items listed in the array on the right side of --
from
the array on the left side of the function, leaving [0]
as the result.
1
2
3
4
%dw 2.0
output application/json
---
{ "a" : [0, 1, 1, 2] -- [1,2] }
1
{ "a": [0] }
--({ (K)?: V }, Object): { (K)?: V }
Removes specified key-value pairs from an object.
Parameters
Name | Description |
---|---|
|
The object to remove. |
|
Objects to remove from the source object. |
Example
This example removes a key-value pair from the source object.
1
2
3
4
%dw 2.0
output application/json
---
{ "hello" : "world", "name" : "DW" } -- { "hello" : "world"}
1
{ "name": "DW" }
--(Object, Array<String>)
Removes specified key-value pairs from an object.
Parameters
Name | Description |
---|---|
|
The source object (an |
|
Keys for the key-value pairs to remove from the source object. |
Example
This example removes two key-value pairs from the source object.
1
2
3
4
%dw 2.0
output application/json
---
{ "yes" : "no", "good" : "bad", "old" : "new" } -- ["yes", "old"]
1
{ "good": "bad" }
--(Object, Array<Key>)
Removes specified key-value pairs from an object.
Parameters
Name | Description |
---|---|
|
The source object (an |
|
A keys for the key-value pairs to remove from the source object. |
Example
This example specifies the key-value pair to remove from the source object.
1
2
3
4
%dw 2.0
output application/json
---
{ "hello" : "world", "name" : "DW" } -- ["hello" as Key]
1
{ "name": "DW" }
1.1.3. abs
abs(Number): Number
Returns the absolute value of a number.
Parameters
Name | Description |
---|---|
|
The number to evaluate. |
Parameters
Name | Description |
---|---|
|
The number to apply the operation to. |
Example
This example returns the absolute value of the specified numbers.
1
2
3
4
%dw 2.0
output application/json
---
[ abs(-2), abs(2.5), abs(-3.4), abs(3) ]
1
[ 2, 2.5, 3.4, 3 ]
1.1.4. avg
avg(Array<Number>): Number
Returns the average of numbers listed in an array.
An array that is empty or that contains a non-numeric value results in an error.
Parameters
Name | Description |
---|---|
|
The input array of numbers. |
Example
This example returns the average of multiple arrays.
1
2
3
4
%dw 2.0
output application/json
---
{ a: avg([1, 1000]), b: avg([1, 2, 3]) }
1
{ "a": 500.5, "b": 2.0 }
1.1.5. ceil
ceil(Number): Number
Rounds a number up to the nearest whole number.
Parameters
Name | Description |
---|---|
|
The number to round. |
Example
This example rounds numbers up to the nearest whole numbers. Notice that 2.1
rounds up to 3
.
1
2
3
4
5
%dw 2.0
output application/json
---
[ ceil(1.5), ceil(2.1), ceil(3) ]
1
[ 2, 3, 3 ]
1.1.6. contains
contains(Array<T>, Any): Boolean
Returns true
if an input contains a given value, false
if not.
This version of contains
accepts an array as input. Other versions
accept a string and can use another string or regular expression to
determine whether there is a match.
Parameters
Name | Description |
---|---|
|
The input array. |
|
Element to find in the array. Can be any supported data type. |
Example
This example finds that 2
is in the input array, so it returns true
.
1
2
3
4
%dw 2.0
output application/json
---
[ 1, 2, 3, 4 ] contains(2)
1
true
Example
This example indicates whether the input array contains '"3"'.
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
{ "ContainsRequestedItem": true }
contains(String, String): Boolean
Indicates whether a string contains a given substring. Returns true
or false
.
Parameters
Name | Description |
---|---|
|
An input string (a |
|
The substring (a |
Example
This example finds "mule" in the input string "mulesoft", so it returns true
.
1
2
3
4
%dw 2.0
output application/json
---
"mulesoft" contains("mule")
1
true
Example
This example finds that the substring "me"
is in "some string"
, so it
returns true
.
1
2
3
4
%dw 2.0
output application/json
---
{ ContainsString : payload.root.mystring contains("me") }
1
2
<?xml version="1.0" encoding="UTF-8"?>
<root><mystring>some string</mystring></root>
1
{ "ContainsString": true }
contains(String, Regex): Boolean
Returns true
if a string contains a match to a regular expression, false
if not.
Parameters
Name | Description |
---|---|
|
An input string. |
|
A Java regular expression for matching characters in the input |
Example
This example checks for any of the letters e
through g
in the input
mulesoft
, so it returns true
.
1
2
3
4
%dw 2.0
output application/json
---
contains("mulesoft", /[e-g]/)
1
true
Example
This example finds a match to /s[t|p]rin/
within "A very long string"
,
so it returns true
. The [t|p]
in the regex means t
or p
.
1
2
3
4
%dw 2.0
output application/json
---
ContainsString: payload.root.mystring contains /s[t|p]rin/
1
2
<?xml version="1.0" encoding="UTF-8"?>
<root><mystring>A very long string</mystring></root>
1
{ "ContainsString": true }
1.1.7. daysBetween
daysBetween(Date, Date): Number
Returns the number of days between two dates.
Parameters
Name | Description |
---|---|
|
From date (a |
|
To date (a |
Example
This example returns the number of days between the specified dates.
1
2
3
4
%dw 2.0
output application/json
---
{ days : daysBetween('2016-10-01T23:57:59-03:00', '2017-10-01T23:57:59-03:00') }
1
{ "days" : 365 }
1.1.8. distinctBy
distinctBy(Array<T>, (item: T, index: Number) → Any): Array<T>
Iterates over an array and returns the unique elements in it.
This version of distinctBy
finds unique values in an array. Other versions
act on an object and handle a null value.
Parameters
Name | Description |
---|---|
|
The array to evaluate. |
|
The criteria used to select an |
Example
This example inputs an array that contains duplicate numbers and returns an
array with unique numbers from that input. Note that you can write the same
expression using an anonymous parameter for the values:
[0, 1, 2, 3, 3, 2, 1, 4] distinctBy $
1
2
3
4
%dw 2.0
output application/json
---
[0, 1, 2, 3, 3, 2, 1, 4] distinctBy (value) -> { "unique" : value }
1
[ 0, 1, 2, 3, 4]
Example
This example removes duplicates of "Kurt Cagle"
from an array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
%dw 2.0
output application/json
var record = {
"title": "XQuery Kick Start",
"author": [
"James McGovern",
"Per Bothner",
"Kurt Cagle",
"James Linn",
"Kurt Cagle",
"Kurt Cagle",
"Kurt Cagle",
"Vaidyanathan Nagarajan"
],
"year":"2000"
}
---
{
"book" : {
"title" : record.title,
"year" : record.year,
"authors" : record.author distinctBy $
}
}
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(Null, (item: Nothing, index: Nothing) → Any): Null
Helper function that allows distinctBy to work with null values.
distinctBy({ (K)?: V }, (value: V, key: K) → Any): Object
Removes duplicate key-value pairs from an object.
Parameters
Name | Description |
---|---|
|
The object from which to remove the key-value pairs. |
|
The |
Example
This example inputs an object that contains duplicate key-value pairs and
returns an object with key-value pairs from that input. Notice that the
keys (a
and A
) are not treated with case sensitivity, but the values
(b
and B
) are. Also note that you can write the same expression using
an anonymous parameter for the values:
{a : "b", a : "b", A : "b", a : "B"} distinctBy $
1
2
3
4
%dw 2.0
output application/json
---
{a : "b", a : "b", A : "b", a : "B"} distinctBy (value) -> { "unique" : value }
1
{ "a": "b", "a": "B" }
Example
This example removes duplicates (<author>James McGovern</author>
)
from <book/>
.
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/xml
---
{
book : {
title : payload.book.title,
authors: payload.book.&author distinctBy $
}
}
1
2
3
4
5
6
7
8
<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
<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): Boolean
Returns true
if a string ends with a provided substring, false
if not.
Parameters
Name | Description |
---|---|
|
The input string (a |
|
The suffix string to find at the end of the input string. |
Example
This example finds "no" (but not "to") at the end of "Mariano".
1
2
3
4
%dw 2.0
output application/json
---
[ "Mariano" endsWith "no", "Mariano" endsWith "to" ]
1
[ true, false ]
1.1.10. entriesOf
entriesOf(T): Array<{| key: Key, value: Any, attributes: Object |}>
Returns an array of key-value pairs that describe the key, value, and any attributes in the input object.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
|
The |
Example
This example returns the key, value, and attributes in the object specified
in the variable myVar
.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Objects
var myVar = read('<xml attr="x"><a>true</a><b>1</b></xml>', 'application/xml')
output application/json
---
{ "entrySet" : entrySet(myVar) }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"entrySet": [
{
"key": "xml",
"value": {
"a": "true",
"b": "1"
},
"attributes": {
"attr": "x"
}
}
]
}
1.1.11. filter
filter(Array<T>, (item: T, index: Number) → Boolean): Array<T>
Iterates over an array and applies an expression that returns matching values.
The expression must return true
or false
. If the expression returns true
for a value or index in the array, the value gets captured in the output array.
If it returns false
for a value or index in the array, that item gets
filtered out of the output. If there are no matches, the output array will
be empty.
Parameters
Name | Description |
---|---|
|
The array to filter. |
|
Boolean expression that selects an |
Example
This example returns an array of values in the array that are greater than 2
.
1
[9,2,3,4,5] filter (value, index) -> (value > 2)
1
[9,3,4,5]
Example
This example returns an array of all values found at an index greater than 2
.
1
[9,2,3,4,5] filter ((value, index) -> (index > 2))
1
[4,5]
Example
This example returns an array of all items found at an index ($$
)
greater than 1
where the value of the element is less than 5
. Notice that
it is using anonymous parameters as selectors instead of using named
parameters in an anonymous function.
1
2
3
4
%dw 2.0
output application/json
---
[9, 2, 3, 4, 5] filter (($$ > 1) and ($ < 5))
1
[3,4]
filter(Null, (item: Nothing, index: Nothing) → Boolean): Null
Helper function that allows filter
to work with null values.
1.1.12. filterObject
filterObject({ (K)?: V }, (value: V, key: K, index: Number) → Boolean): { (K)?: V }
Iterates a list of key-value pairs in an object and applies an expression that returns only matching objects, filtering out the rest from the output.
The expression must return true
or false
. If the expression returns true
for a key, value, or index of an object, the object gets captured in the
output. If it returns false
for any of them, the object gets filtered out
of the output. If there are no matches, the output array will be empty.
Parameters
Name | Description |
---|---|
|
The source object to evaluate. |
|
Boolean expression that selects a |
Example
This example outputs an object if its value equals "apple"
.
1
2
3
4
%dw 2.0
output application/json
---
{"a" : "apple", "b" : "banana"} filterObject ((value) -> value == "apple")
1
{ "a": "apple" }
Example
This example only outputs an object if the key starts with "letter". The
DataWeave startsWith
function returns true
or false
. Note that you can
use the anonymous parameter for the key to write the expression
((value, key) → key startsWith "letter")
: ($$ startsWith "letter")`
1
2
3
4
%dw 2.0
output application/json
---
{"letter1": "a", "letter2": "b", "id": 1} filterObject ((value, key) -> key startsWith "letter")
1
{ "letter1": "a", "letter2": "b" }
Example
This example only outputs an object if the index of the object in the array
is less than 1, which is always true of the first object. Note that you can
use the anonymous parameter for the index to write the expression
((value, key, index) → index < 1)
: ($$$ < 1)
1
2
3
4
%dw 2.0
output application/json
---
{ "1": "a", "2": "b", "3": "c"} filterObject ((value, key, index) -> index < 1)
1
{ "1": "a" }
filterObject(Null, (value: Nothing, key: Nothing, index: Nothing) → Boolean): Null
Helper function that allows filterObject
to work with null values.
1.1.13. find
find(Array<T>, Any): Array<Number>
Returns indices of an input that match a specified value.
This version of the function returns indices of an array. Others return indices of a string.
Parameters
Name | Description |
---|---|
|
An array with elements of any type. |
|
Value to find in the input array. |
Example
This example finds the index of an element in a string array.
1
2
3
4
%dw 2.0
output application/json
---
["Bond", "James", "Bond"] find "Bond"
1
[0,2]
find(String, Regex): Array<Array<Number>>
Returns the indices in the text that match the specified regular expression (regex), followed by the capture groups.
The first element in each resulting sub-array is the index in the text that matches the regex, and the next ones are the capture groups in the regex (if present).
Note: To retrieve parts of the text that match a regex. use the scan
function.
Parameters
Name | Description |
---|---|
|
A string. |
|
A Java regular expression for matching characters in the |
Example
This example finds the beginning and ending indices of words that contain ea
1
2
3
4
%dw 2.0
output application/json
---
"I heart DataWeave" find /\w*ea\w*(\b)/
1
[ [2,7], [8,17] ]
find(String, String): Array<Number>
Lists indices where the specified characters of a string are present.
Parameters
Name | Description |
---|---|
|
A source string. |
|
The string to find in the source string. |
Example
This example lists the indices of "a" found in "aabccdbce".
1
2
3
4
%dw 2.0
output application/json
---
"aabccdbce" find "a"
1
[0,1]
1.1.14. flatMap
flatMap(Array<T>, (item: T, index: Number) → Array<R>): Array<R>
Iterates over each item in an array and flattens the results.
Instead of returning an array of arrays (as map
does when you iterate over
the values within an input like [ [1,2], [3,4] ]
), flatMap
returns a
flattened array that looks like this: [1, 2, 3, 4]
. flatMap
is similar to
flatten
, but flatten
only acts on the values of the arrays, while
flatMap
can act on values and indices of items in the array.
Parameters
Name | Description |
---|---|
|
The array to map. |
|
Expression or selector for an |
Example
This example returns an array containing each value in order. Though it names
the optional index
parameter in its anonymous function
(value, index) → value
, it does not use index
as a selector for the
output, so it is possible to write the anonymous function using
(value) → value
. You can also use an anonymous parameter for the
value to write the example like this: [ [3,5], [0.9,5.5] ] flatMap $
.
Note that this example produces the same result as
flatten([ [3,5], [0.9,5.5] ])
, which uses flatten
.
1
2
3
4
%dw 2.0
output application/json
---
[ [3,5], [0.9,5.5] ] flatMap (value, index) -> value
1
[ 3, 5, 0.9, 5.5]
flatMap(Null, (item: Nothing, index: Nothing) → Any): Null
Helper function that allows flatMap
to work with null values.
1.1.15. flatten
flatten(Array<Array<T> | Q>): Array<T | Q>
Turns a nested array (such as [ [1,2,3], [4,5,6] ]
) into a single array containing all values(such as [1, 2, 3, 4, 5, 6]
).
Parameters
Name | Description |
---|---|
|
The input array of arrays made up of any supported types. |
Example
This example defines three arrays of numbers, creates another array containing those three arrays, and then uses the flatten function to convert the array of arrays into a single array with all values.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
var array1 = [1,2,3]
var array2 = [4,5,6]
var array3 = [7,8,9]
var arrayOfArrays = [array1, array2, array3]
---
flatten(arrayOfArrays)
1
[ 1,2,3,4,5,6,7,8,9 ]
Example
This example returns a single array from a nested array of objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
%dw 2.0
var myData =
{ user : [
{
group : "dev",
myarray : [
{ name : "Shoki", id : 5678 },
{ name : "Mariano", id : 9123 }
]
}
]
}
output application/json
---
flatten(myData.user.myarray)
1
2
3
4
5
6
7
8
9
10
[
{
"name": "Shoki",
"id": 5678
},
{
"name": "Mariano",
"id": 9123
}
]
Note that
if you use myData.user.myarray
to select the array of objects in myarray
,
instead of using flatten(myData.user.myarray)
, the output is a nested array of objects:
1
2
3
4
5
6
7
8
9
10
11
12
[
[
{
"name": "Shoki",
"id": 5678
},
{
"name": "Mariano",
"id": 9123
}
]
]
flatten(Null): Null
Helper function that allows flatten to work with null values.
1.1.16. floor
floor(Number): Number
Rounds a number down to the nearest whole number.
Parameters
Name | Description |
---|---|
|
The number to evaluate. |
Example
This example rounds numbers down to the nearest whole numbers. Notice that
1.5
rounds down to 1
.
1
2
3
4
%dw 2.0
output application/json
---
[ floor(1.5), floor(2.2), floor(3) ]
1
[ 1, 2, 3]
1.1.17. groupBy
groupBy(Array<T>, (item: T, index: Number) → R): { ®: Array<T> }
Returns an object that groups items from an array based on specified criteria, such as an expression or matching selector.
This version of groupBy
groups the elements of an array using the
criteria
function. Other versions act on objects and handle null values.
Parameters
Name | Description |
---|---|
|
The array to group. |
|
Expression providing the criteria by which to group the items in the array. |
Example
This example groups items from the input array ["a","b","c"]
by their
indices. Notice that it returns the numeric indices as strings and that items
(or values) of the array are returned as arrays, in this case, with a single
item each. The items in the array are grouped based on an anonymous function
(item, index) → index
that uses named parameters (item
and index
).
Note that you can produce the same result using the anonymous parameter
$$
to identify the indices of the array like this:
["a","b","c"] groupBy $$
1
2
3
4
%dw 2.0
output application/json
---
["a","b","c"] groupBy (item, index) -> index
1
{ "2": [ "c" ], "1": [ "b" ], "0": [ "a" ] }
Example
This example groups the elements of an array based on the language field.
Notice that it uses the item.language
selector to specify the grouping
criteria. So the resulting object uses the "language" values ("Scala"
and
"Java"
) from the input to group the output. Also notice that the output
places the each input object in an array.
1
2
3
4
5
6
7
8
9
%dw 2.0
var myArray = [
{ "name": "Foo", "language": "Java" },
{ "name": "Bar", "language": "Scala" },
{ "name": "FooBar", "language": "Java" }
]
output application/json
---
myArray groupBy (item) -> item.language
1
2
3
4
5
6
7
8
9
{
"Scala": [
{ "name": "Bar", "language": "Scala" }
],
"Java": [
{ "name": "Foo", "language": "Java" },
{ "name": "FooBar", "language": "Java" }
]
}
Example
This example uses groupBy "myLabels"`to return an object where `"mylabels"
is the key, and an array of selected values
(["Open New", "Zoom In", "Zoom Out", "Original View" ]
) is the value. It
uses the selectors (myVar.menu.items.*label
) to create that array. Notice
that the selectors retain all values where "label"
is the key but filter
out values where "id"
is the key.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
var myVar = { menu: {
header: "Move Items",
items: [
{"id": "internal"},
{"id": "left", "label": "Move Left"},
{"id": "right", "label": "Move Right"},
{"id": "up", "label": "Move Up"},
{"id": "down", "label": "Move Down"}
]
}}
output application/json
---
(myVar.menu.items.*label groupBy "myLabels")
1
{ "myLabels": [ "Move Left", "Move Right", "Move Up", "Move Down" ] }
groupBy({ (K)?: V }, (value: V, key: K) → R): { ®: { (K)?: V } }
Groups elements of an object based on criteria that the groupBy
uses to iterate over elements in the input.
Parameters
Name | Description |
---|---|
|
The object containing objects to group. |
|
The grouping criteria to apply to elements in the input object, such as a |
Example
This example groups objects within an array of objects using the anonymous
parameter $
for the value of each key in the input objects. It applies
the DataWeave upper
function to those values. In the output, these values
become upper-case keys. Note that you can also write the same example using
a named parameter for the within an anonymous function like this:
{ "a" : "b", "c" : "d"} groupBy (value) → upper(value)
1
2
3
4
%dw 2.0
output application/json
---
{ "a" : "b", "c" : "d"} groupBy upper($)
1
{ "D": { "c": "d" }, "B": { "a": "b" } }
Example
This example uses groupBy "costs"
to produce a JSON object from an XML object
where "costs"
is the key, and the selected values of the XML element prices
becomes the JSON value ({ "price": "9.99", "price": "10.99" }
).
1
2
3
4
5
6
%dw 2.0
var myRead =
read("<prices><price>9.99</price><price>10.99</price></prices>","application/xml")
output application/json
---
myRead.prices groupBy "costs"
1
{ "costs" : { "price": "9.99", "price": "10.99" } }
groupBy(Null, (Nothing, Nothing) → Any): Null
Helper function that allows groupBy to work with null values.
1.1.18. isBlank
isBlank(String | Null): Boolean
Returns true
if the given string is empty or completely composed of whitespace,
false
if not.
Parameters
Name | Description |
---|---|
|
A input string to evaluate. |
Example
This example indicates whether the given values are blank. It also
uses the not
and !
operators to check that a value is not blank.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
output application/json
---
{
"empty" : isBlank(""),
"withSpaces" : isBlank(" "),
"withText" : isBlank(" 1223"),
// not blank
"checkNotEmpty" : not isBlank(" 1234"),
// ! for not in DataWeave 2.2.0 for Mule 4.2 and later
"checkNotEmptyTwo" : ! isBlank(" 1234")
}
1
2
3
4
5
6
7
{
"empty": true,
"withSpaces": true,
"withText": false,
"checkNotEmpty": true,
"checkNotEmptyTwo": true
}
1.1.19. isDecimal
isDecimal(Number): Boolean
Returns true
if the given number contains a decimal, false
if not.
Parameters
Name | Description |
---|---|
|
The number to evaluate. |
Example
This example indicates whether a number has a decimal. Note that numbers within strings get coerced to numbers.
1
2
3
4
%dw 2.0
output application/json
---
[ isDecimal(1.1), isDecimal(1), isDecimal("1.1") ]
1
[ true, false, true ]
1.1.20. isEmpty
isEmpty(Array<Any>): Boolean
Returns true
if the given input value is empty, false
if not.
This version of isEmpty
acts on an array. Other versions
act on a string or object, and handle null values.
Parameters
Name | Description |
---|---|
|
The input array to evaluate. |
Example
This example indicates whether the input array is empty.
1
2
3
4
%dw 2.0
output application/json
---
[ isEmpty([]), isEmpty([1]) ]
1
[ true, false ]
isEmpty(String): Boolean
Returns true
if the input string is empty, false
if not.
Parameters
Name | Description |
---|---|
|
A string to evaluate. |
Example
This example indicates whether the input strings are empty.
1
2
3
4
%dw 2.0
output application/json
---
[ isEmpty(""), isEmpty("DataWeave") ]
1
[ true, false ]
isEmpty(Null): Boolean
Returns true
if the input is null
.
Parameters
Name | Description |
---|---|
|
|
Example
This example indicates whether the input is null
.
1
2
3
4
%dw 2.0
output application/json
---
{ "nullValue" : isEmpty(null) }
1
{ "nullValue": true }
isEmpty(Object): Boolean
Returns true
if the given object is empty, false
if not.
Parameters
Name | Description |
---|---|
|
The object to evaluate. |
Example
This example indicates whether the input objects are empty.
1
2
3
4
%dw 2.0
output application/json
---
[ isEmpty({}), isEmpty({name: "DataWeave"}) ]
1
[ true, false ]
1.1.21. isEven
isEven(Number): Boolean
Returns true
if the number or numeric result of a mathematical operation is
even, false
if not.
Parameters
Name | Description |
---|---|
|
The number to evaluate. |
Example
This example indicates whether the numbers and result of an operation are even.
1
2
3
4
%dw 2.0
output application/json
---
{ "isEven" : [ isEven(0), isEven(1), isEven(1+1) ] }
1
{ "isEven" : [ true, false, true ] }
1.1.22. isInteger
isInteger(Number): Boolean
Returns true
if the given number is an integer (which lacks decimals),
false
if not.
Parameters
Name | Description |
---|---|
|
The number to evaluate. |
Example
This example indicates whether the input is an integer. Note numbers within strings get coerced to numbers.
1
2
3
4
%dw 2.0
output application/json
---
[ isLeapYear(locDT1), isLeapYear(locDT2), isInteger("1") ]
1
[ false, true, true ]
1.1.23. isLeapYear
isLeapYear(DateTime): Boolean
Returns true
if it receives a date for a leap year, false
if not.
This version of leapYear
acts on a DateTime
type. Other versions act on
the other date and time formats that DataWeave supports.
Parameters
Name | Description |
---|---|
|
The |
Example
This example indicates whether the input is a leap year.
1
2
3
4
%dw 2.0
output application/json
---
[ isLeapYear(|2016-10-01T23:57:59|), isLeapYear(|2017-10-01T23:57:59|) ]
1
[ true, false ]
isLeapYear(Date): Boolean
Returns true
if the input Date
is a leap year, 'false' if not.
Parameters
Name | Description |
---|---|
|
The |
Example
This example indicates whether the input is a leap year.
1
2
3
4
%dw 2.0
output application/json
---
[ isLeapYear(|2016-10-01|), isLeapYear(|2017-10-01|) ]
1
[ true, false ]
isLeapYear(LocalDateTime): Boolean
Returns true
if the input local date-time is a leap year, 'false' if not.
Parameters
Name | Description |
---|---|
|
A |
Example
This example indicates whether the input is a leap year. It uses a map
function to iterate through the array of its LocalDateTime
values,
applies the isLeapYear
to those values, returning the results in an array.
1
2
3
4
%dw 2.0
output application/json
---
[ |2016-10-01T23:57:59-03:00|, |2016-10-01T23:57:59Z| ] map isLeapYear($)
1
[ true, true ]
1.1.24. isOdd
isOdd(Number): Boolean
Returns true
if the number or numeric result of a mathematical operation is
odd, false
if not.
Parameters
Name | Description |
---|---|
|
A number to evaluate. |
Example
This example indicates whether the numbers are odd.
1
2
3
4
%dw 2.0
output application/json
---
{ "isOdd" : [ isOdd(0), isOdd(1), isOdd(2+2) ] }
1
{ "isOdd": [ false, true, false ] }
1.1.25. joinBy
joinBy(Array<StringCoerceable>, String): String
Merges an array into a single string value and uses the provided string as a separator between each item in the list.
Note that joinBy
performs the opposite task of splitBy
.
Parameters
Name | Description |
---|---|
|
The input array. |
|
A |
Example
This example joins the elements with a hyphen (-
).
1
2
3
4
%dw 2.0
output application/json
---
{ "hyphenate" : ["a","b","c"] joinBy "-" }
1
{ "hyphenate": "a-b-c" }
1.1.26. keysOf
keysOf(T): ?
Returns an array of keys from the given object.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
|
The object to evaluate. |
Example
This example returns the keys from the input object.
1
2
3
4
5
%dw 2.0
import * from dw::core::Objects
output application/json
---
{ "keySet" : keySet({ "a" : true, "b" : 1}) }
1
{ "keySet" : ["a","b"] }
Example
This example illustrates a difference between keySet
and nameSet
.
Notice that keySet
retains the attributes (name
and lastName
)
and namespaces (xmlns
) from the XML input, while nameSet
returns
null
for them because it does not retain them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
var myVar = read('<users xmlns="http://test.com">
<user name="Mariano" lastName="Achaval"/>
<user name="Stacey" lastName="Duke"/>
</users>', 'application/xml')
output application/json
---
{ keySetExample: flatten([keysOf(myVar.users) map $.#,
keysOf(myVar.users) map $.@])
}
++
{ nameSet: flatten([namesOf(myVar.users) map $.#,
namesOf(myVar.users) map $.@])
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"keySet": [
"http://test.com",
"http://test.com",
{
"name": "Mariano",
"lastName": "Achaval"
},
{
"name": "Stacey",
"lastName": "Duke"
}
],
"nameSet": [
null,
null,
null,
null
]
}
1.1.27. log
log(String, T): T
Without changing the value of the input, log
returns the input as a system
log.
Use this function to help with debugging DataWeave scripts. A Mule app
outputs the results through the DefaultLoggingService
, which you can see
in the Studio console.
Parameters
Name | Description |
---|---|
|
An optional string that typically describes the log. |
|
The value to log. |
Example
This example logs the specified message. Note that the DefaultLoggingService
in a Mule app that is running in Studio returns the message
WARNING - "Houston, we have a problem," adding the dash `-
between the
prefix and value. The Logger component’s LoggerMessageProcessor
returns
the input string "Houston, we have a problem."
, without the WARNING
prefix.
1
2
3
4
%dw 2.0
output application/json
---
log("WARNING", "Houston, we have a problem.")
1
WARNING - "Houston, we have a problem."
1.1.28. lower
lower(String): String
Returns the provided string in lowercase characters.
Parameters
Name | Description |
---|---|
|
The input string. |
Parameters
Name | Description |
---|---|
|
A string. |
Example
This example converts uppercase characters to lower-case.
1
2
3
4
%dw 2.0
output application/json
---
{ "name" : lower("MULESOFT") }
1
{ "name": "mulesoft" }
lower(Null): Null
Helper function that allows lower to work with null values.
1.1.29. map
map(Array<T>, (item: T, index: Number) → R): Array<R>
Iterates over items in an array and outputs the results into a new array.
Parameters
Name | Description |
---|---|
|
The array to map. |
|
Expression or selector used to act on each |
Example
This example iterates over an input array (["jose", "pedro", "mateo"]
) to
produce an array of DataWeave objects. The anonymous function
(value, index) → {index: value}
maps each item in the input to an object.
As {index: value}
shows, each index from the input array becomes a key
for an output object, and each value of the input array becomes the value of
that object.
1
2
3
4
%dw 2.0
output application/json
---
["jose", "pedro", "mateo"] map (value, index) -> { (index) : value}
1
[ { "0": "jose" }, { "1": "pedro" }, { "2": "mateo" } ]
Example
This example iterates over the input array (['a', 'b', 'c']
) using
an anonymous function that acts on the items and indices of the input. For
each item in the input array, it concatenates the index + 1
(index
plus 1)
with an underscore (_
), and the corresponding value
to return the array,
[ "1_a", "2_b", "3_c" ]
.
1
2
3
4
%dw 2.0
output application/json
---
['a', 'b', 'c'] map ((value, index) -> (index + 1) ++ '_' ++ value)
1
[ "1_a", "2_b", "3_c" ]
Example
If the parameters of the mapper
function are not named, the index can be
referenced with $$
, and the value with $
. This example
iterates over each item in the input array ['joe', 'pete', 'matt']
and returns an array of objects where the index is selected as the key.
The value of each item in the array is selected as the value of
the returned object. Note that the quotes around $$
are necessary to convert the numeric keys to strings.
1
2
3
4
%dw 2.0
output application/json
---
['joe', 'pete', 'matt'] map ( "$$" : $)
1
2
3
4
5
[
{ "0": "joe" },
{ "1": "pete" },
{ "2": "matt" }
]
map(Null, (item: Nothing, index: Nothing) → Any): Null
Helper function that allows map
to work with null
values.
1.1.30. mapObject
mapObject({ (K)?: V }, (value: V, key: K, index: Number) → Object): Object
Iterates over an object using a mapper that acts on keys, values, or indices of that object.
Parameters
Name | Description |
---|---|
|
The object to map. |
|
Expression or selector that provides the |
Example
This example iterates over the input { "a":"b","c":"d"}
and uses the
anonymous mapper function ((value,key,index) → { (index) : { (value):key} }
)
to invert the keys and values in each specified object and to return the
indices of the objects as keys. The mapper uses named parameters to identify
the keys, values, and indices of the input object. Note that you can write
the same expression using anonymous parameters, like this:
{"a":"b","c":"d"} mapObject { ($$$) : { ($):$$} }
1
2
3
4
%dw 2.0
output application/json
---
{"a":"b","c":"d"} mapObject (value,key,index) -> { (index) : { (value):key} }
1
{ "0": { "b": "a" }, "1": { "d": "c" } }
Example
This example increases each price by 5 and formats the numbers to always include 2 decimals.
1
2
3
4
5
6
7
8
%dw 2.0
output application/xml
---
{
prices: payload.prices mapObject (value, key) -> {
(key): (value + 5) as Number {format: "##.00"}
}
}
1
2
3
4
5
6
<?xml version='1.0' encoding='UTF-8'?>
<prices>
<basic>9.99</basic>
<premium>53</premium>
<vip>398.99</vip>
</prices>
1
2
3
4
5
6
<?xml version='1.0' encoding='UTF-8'?>
<prices>
<basic>14.99</basic>
<premium>58.00</premium>
<vip>403.99</vip>
</prices>
mapObject(Null, (value: Nothing, key: Nothing, index: Nothing) → Any): Null
Helper function that allows mapObject
to work with null values.
Example
Using the previous example, you can test that if the input of the mapObject
is null
, the output result is null
as well. In XML null
values are
written as empty tags. You can change these values by using the writer
property writeNilOnNull=true
.
1
2
3
<?xml version='1.0' encoding='UTF-8'?>
<prices>
</prices>
1
2
3
<?xml version='1.0' encoding='UTF-8'?>
<prices>
</prices>
1.1.31. match
match(String, Regex): Array<String>
Uses a Java regular expression (regex) to match a string and then separates it into capture groups. Returns the results in an array.
Note that you can use match
for pattern matching expressions that include
case
statements.
Parameters
Name | Description |
---|---|
|
A string. |
|
A Java regex for matching characters in the |
Example
In this example, the regex matches the input email address and contains two
capture groups within parentheses (located before and after the @
). The
result is an array of elements: The first matching the entire regex, the
second matching the initial capture group () in the the regex, the
third matching the last capture group (
[a-z]
).
1
2
3
4
%dw 2.0
output application/json
---
"me@mulesoft.com" match(/([a-z]*)@([a-z]*).com/)
1
2
3
4
5
[
"me@mulesoft.com",
"me",
"mulesoft"
]
Example
This example outputs matches to values in an array that end in 4
. It uses
flatMap
to iterate over and flatten the list.
1
2
3
4
5
6
7
%dw 2.0
var a = '192.88.99.0/24'
var b = '192.168.0.0/16'
var c = '192.175.48.0/24'
output application/json
---
[ a, b, c ] flatMap ( $ match(/.*[$4]/) )
1
[ "192.88.99.0/24", "192.175.48.0/24" ]
1.1.32. matches
matches(String, Regex): Boolean
Checks if an expression matches the entire input string.
For use cases where you need to output or conditionally process the matched value, see Pattern Matching in DataWeave.
Parameters
Name | Description |
---|---|
|
The input string. |
|
A Java regular expression for matching characters in the string. |
Example
This example indicates whether the regular expression matches the input text.
Note that you can also use the matches(text,matcher)
notation (for example,
matches("admin123", /a.*\d+/)
).
1
2
3
4
%dw 2.0
output application/json
---
[ ("admin123" matches /a.*\d+/), ("admin123" matches /^b.+/) ]
1
[ true, false ]
1.1.33. max
max(Array<T>): T | Null
Returns the highest Comparable
value in an array.
The items must be of the same type, or the function throws an error. The
function returns null
if the array is empty.
Parameters
Name | Description |
---|---|
|
The input array. The elements in the array can be any supported type. |
Example
This example returns the maximum value of each input array.
1
2
3
4
%dw 2.0
output application/json
---
{ a: max([1, 1000]), b: max([1, 2, 3]), c: max([1.5, 2.5, 3.5]) }
1
{ "a": 1000, "b": 3, "c": 3.5 }
1.1.34. maxBy
maxBy(Array<T>, (item: T) → Comparable): T | Null
Iterates over an array and returns the highest value of
Comparable
elements from it.
The items need to be of the same type or maxBy
throws an error. The function
returns null
when the array is empty.
Parameters
Name | Description |
---|---|
|
The input array. |
|
Expression for selecting an item from the array, where the item is a |
Example
This example returns the greatest numeric value within objects
(key-value pairs) in an array. Notice that it uses item.a
to select the
value of the object. You can also write the same expression like this, using
an anonymous parameter:
[ { "a" : 1 }, { "a" : 3 }, { "a" : 2 } ] maxBy $.a
1
2
3
4
%dw 2.0
output application/json
---
[ { "a" : 1 }, { "a" : 3 }, { "a" : 2 } ] maxBy ((item) -> item.a)
1
{ "a" : 3 }
Example
This example gets the latest DateTime
, Date
, and Time
from inputs
defined in the variables myDateTime1
and myDateTime2
. It also shows that
the function returns null on an empty array.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
var myDateTime1 = "2017-10-01T22:57:59-03:00"
var myDateTime2 = "2018-10-01T23:57:59-03:00"
output application/json
---
{
myMaxBy: {
byDateTime: [ myDateTime1, myDateTime2 ] maxBy ((item) -> item),
byDate: [ myDateTime1 as Date, myDateTime2 as Date ] maxBy ((item) -> item),
byTime: [ myDateTime1 as Time, myDateTime2 as Time ] maxBy ((item) -> item),
emptyArray: [] maxBy ((item) -> item)
}
}
1
2
3
4
5
6
7
8
{
"myMaxBy": {
"byDateTime": "2018-10-01T23:57:59-03:00",
"byDate": "2018-10-01",
"byTime": "23:57:59-03:00",
"emptyArray": null
}
}
1.1.35. min
min(Array<T>): T | Null
Returns the lowest Comparable
value in an array.
The items need to be of the same type or min
throws an error. The function
returns null when the array is empty.
Parameters
Name | Description |
---|---|
|
The input array. The elements in the array can be any supported type. |
Example
This example returns the lowest numeric value of each input array.
1
2
3
4
%dw 2.0
output application/json
---
{ a: min([1, 1000]), b: min([1, 2, 3]), c: min([1.5, 2.5, 3.5]) }
1
{ "a": 1, "b": 1, "c": 1.5 }
1.1.36. minBy
minBy(Array<T>, (item: T) → Comparable): T | Null
Iterates over an array to return the lowest value of comparable elements from it.
The items need to be of the same type. minBy
returns an error if they are
not, and it returns null when the array is empty.
Parameters
Name | Description |
---|---|
|
Element in the input array (of type |
Example
This example returns the lowest numeric value within objects
(key-value pairs) in an array. Notice that it uses item.a
to select the
value of the object. You can also write the same expression like this, using
an anonymous parameter:
[ { "a" : 1 }, { "a" : 3 }, { "a" : 2 } ] minBy $.a
1
2
3
4
%dw 2.0
output application/json
---
[ { "a" : 1 }, { "a" : 2 }, { "a" : 3 } ] minBy (item) -> item.a
1
{ "a" : 1 }
Example
This example gets the latest DateTime
, Date
, and Time
from inputs
defined in the variables myDateTime1
and myDateTime2
. It also shows that
the function returns null on an empty array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
var myDateTime1 = "2017-10-01T22:57:59-03:00"
var myDateTime2 = "2018-10-01T23:57:59-03:00"
output application/json
---
{
myMinBy: {
byDateTime: [ myDateTime1, myDateTime2 ] minBy ((item) -> item),
byDate: [ myDateTime1 as Date, myDateTime2 as Date ] minBy ((item) -> item),
byTime: [ myDateTime1 as Time, myDateTime2 as Time ] minBy ((item) -> item),
aBoolean: [ true, false, (0 > 1), (1 > 0) ] minBy $,
emptyArray: [] minBy ((item) -> item)
}
}
1
2
3
4
5
6
7
8
9
{
"myMinBy": {
"byDateTime": "2017-10-01T22:57:59-03:00",
"byDate": "2017-10-01",
"byTime": "22:57:59-03:00",
"aBoolean": false,
"emptyArray": null
}
}
1.1.37. mod
mod(Number, Number): Number
Returns the modulo (the remainder after dividing the dividend
by the divisor
).
Parameters
Name | Description |
---|---|
|
The number that serves as the dividend for the operation. |
|
The number that serves as the divisor for the operation. |
Example
This example returns the modulo of the input values. Note that you can also
use the mod(dividend, divisor)
notation (for example, mod(3, 2)
to return
1
).
1
2
3
4
%dw 2.0
output application/json
---
[ (3 mod 2), (4 mod 2), (2.2 mod 2) ]
1
[ 1, 0, 0.2]
1.1.38. namesOf
namesOf(Object): Array<String>
Returns an array of strings with all the name of the keys from the given object.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
|
The object to evaluate. |
Example
This example returns the keys from the input object.
1
2
3
4
%dw 2.0
output application/json
---
{ "namesOf" : namesOf({ "a" : true, "b" : 1}) }
1
{ "namesOf" : ["a","b"] }
1.1.39. native
native(String): Nothing
Internal method used to indicate that a function implementation is not written in DataWeave but in Scala.
1.1.40. now
now(): DateTime
Returns a DateTime
value for the current date and time.
Example
This example uses now()
to return the current date and time as a
DateTime
value. It also shows how to return a date and time
in a specific time zone. Java 8 time zones are supported.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
nowCalled: now(),
nowCalledSpecificTimeZone: now() >> "America/New_York"
}
1
2
3
4
{
"nowCalled": "2019-08-26T13:32:10.64-07:00",
"nowCalledSpecificTimeZone": "2019-08-26T16:32:10.643-04:00"
}
Example
This example shows uses of the now()
function with valid
selectors. It also shows how to get the epoch time with now() as Number
.
For additional examples, see
Date and Time (dw::Core Types).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
%dw 2.0
output application/json
---
{
now: now(),
epochTime : now() as Number,
nanoseconds: now().nanoseconds,
milliseconds: now().milliseconds,
seconds: now().seconds,
minutes: now().minutes,
hour: now().hour,
day: now().day,
month: now().month,
year: now().year,
quarter: now().quarter,
dayOfWeek: now().dayOfWeek,
dayOfYear: now().dayOfYear,
offsetSeconds: now().offsetSeconds,
formattedDate: now() as String {format: "y-MM-dd"},
formattedTime: now() as String {format: "hh:m:s"}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"now": "2019-06-18T16:55:46.678-07:00",
"epochTime": 1560902146,
"nanoseconds": 678000000,
"milliseconds": 678,
"seconds": 46,
"minutes": 55,
"hour": 16,
"day": 18,
"month": 6,
"year": 2019,
"quarter": 2,
"dayOfWeek": 2,
"dayOfYear": 169,
"offsetSeconds": -25200,
"formattedDate": "2019-06-18",
"formattedTime": "04:55:46"
}
1.1.41. orderBy
orderBy(O, (value: V, key: K) → R): O
Reorders the elements of an input using criteria that acts on selected elements of that input.
This version of orderBy
takes an object as input. Other versions act on an
input array or handle a null value.
Note that you can reference the index with the anonymous parameter
$$
and the value with $
.
Parameters
Name | Description |
---|---|
|
The object to reorder. |
|
The result of the function is used as the criteria to reorder the object. |
Example
This example alphabetically orders the values of each object in the input
array. Note that orderBy($.letter)
produces the same result as
orderBy($[0])
.
1
2
3
4
%dw 2.0
output application/json
---
[{ letter: "e" }, { letter: "d" }] orderBy($.letter)
1
2
3
4
5
6
7
8
[
{
"letter": "d"
},
{
"letter": "e"
}
]
Example
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>, (item: T, index: Number) → R): Array<T>
Sorts an array using the specified criteria.
Parameters
Name | Description |
---|---|
|
The array to sort. |
|
The result of the function will be used as the criteria to sort the list. It should return a simple value (String, Number, etc) |
Example
This example sorts an array of numbers based on the numeric values.
1
2
3
4
%dw 2.0
output application/json
---
[3,2,3] orderBy $
1
[ 2, 3, 3 ]
Example
This example sorts an array of people based on their age.
1
2
3
4
%dw 2.0
output application/json
---
[{name: "Santiago", age: 42},{name: "Leandro", age: 29}, {name: "Mariano", age: 35}] orderBy (person) -> person.age
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
{
name: "Leandro",
age: 29
},
{
name: "Mariano",
age: 35
},
{
name: "Santiago",
age: 42
}
]
orderBy(Null, (item: Nothing, index: Nothing) → Null): Null
Helper function that allows orderBy to work with null values.
1.1.42. pluck
pluck({ (K)?: V }, (value: V, key: K, index: Number) → R): Array<R>
Useful for mapping an object into an array, pluck
iterates over an object
and returns an array of keys, values, or indices from the object.
It is an alternative to mapObject
, which is similar but returns
an object, instead of an array.
Parameters
Name | Description |
---|---|
|
The object to map. |
|
Expression or selector that provides the |
Example
This example iterates over { "a":"b","c":"d"}
using the
anonymous mapper function ((value,key,index) → { (index) : { (value):key} }
)
to invert each key-value pair in the specified object and to return their
indices as keys. The mapper uses named parameters to identify
the keys, values, and indices of the object. Note that you can write
the same expression using anonymous parameters, like this:
{"a":"b","c":"d"} pluck { ($$$) : { ($):$$} }
Unlike the almost identical example that uses mapObject
, pluck
returns
the output as an array.
1
2
3
4
%dw 2.0
output application/json
---
{"a":"b","c":"d"} pluck (value,key,index) -> { (index) : { (value):key} }
1
[ { "0": { "b": "a" } }, { "1": { "d": "c" } } ]
Example
This example uses pluck
to iterate over each element within <prices/>
and returns arrays of their keys, values, and indices. It uses anonymous
parameters to capture them. Note that it uses as Number
to convert the
values to numbers. Otherwise, they would return as strings.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
output application/json
var readXml = read("<prices>
<basic>9.99</basic>
<premium>53.00</premium>
<vip>398.99</vip>
</prices>", "application/xml")
---
"result" : {
"keys" : readXml.prices pluck($$),
"values" : readXml.prices pluck($) as Number,
"indices" : readXml.prices pluck($$$)
}
1
2
3
4
5
6
7
{
"result": {
"keys": [ "basic", "premium", "vip" ],
"values": [ 9.99, 53, 398.99 ],
"indices": [ 0, 1, 2 ]
}
}
pluck(Null, (value: Nothing, key: Nothing, index: Nothing) → Any): Null
Helper function that allows pluck to work with null values.
1.1.43. pow
pow(Number, Number): Number
Raises the value of a base
number to the specified power
.
Parameters
Name | Description |
---|---|
|
A number ( |
|
A number ( |
Example
This example raises the value a base
number to the specified power
.
Note that you can also use the pow(base,power)
notation (for example,
pow(2,3)
to return 8
).
1
2
3
4
%dw 2.0
output application/json
---
[ (2 pow 3), (3 pow 2), (7 pow 3) ]
1
[ 8, 9, 343 ]
1.1.44. random
random(): Number
Returns a pseudo-random number greater than or equal to 0.0
and less than 1.0
.
Example
This example generates a pseudo-random number and multiplies it by 1000.
1
2
3
4
%dw 2.0
output application/json
---
{ price: random() * 1000 }
1
{ "price": 65.02770292248383 }
1.1.45. randomInt
randomInt(Number): Number
Returns a pseudo-random whole number from 0
to the specified number
(exclusive).
Parameters
Name | Description |
---|---|
|
A number that sets the upper bound of the random number. |
Example
This example returns an integer from 0 to 1000 (exclusive).
1
2
3
4
%dw 2.0
output application/json
---
{ price: randomInt(1000) }
1
{ "price": 442.0 }
1.1.46. read
read(String | Binary, String, Object): Any
Reads a string or binary and returns parsed content.
This function can be useful if the reader cannot determine the content type by default.
Parameters
Name | Description |
---|---|
|
The string or binary to read. |
|
A supported format (or content type). Default: |
|
Optional: Sets reader configuration properties. For other formats and reader configuration properties, see DataWeave Output Formats and Writer Properties. |
Example
This example reads a JSON object { "hello" : "world" }'
, and it uses the
"application/json"
argument to indicate input content type. By contrast,
the output application/xml
directive in the header of the script tells the
script to transform the JSON content into XML output. Notice that the XML
output uses hello
as the root XML element and world
as the value of
that element. The hello
in the XML corresponds to the key "hello"
in the JSON object, and world
corresponds to the JSON value "world"
.
1
2
3
4
%dw 2.0
output application/xml
---
read('{ "hello" : "world" }','application/json')
1
<?xml version='1.0' encoding='UTF-8'?><hello>world</hello>
Example
This example reads a string as a CSV format without a header and transforms it
to JSON. Notice that it adds column names as keys to the output object. Also,
it appends [0]
to the function call here to select the first index of the
resulting array, which avoids producing the results within an array (with
square brackets surrounding the entire output object).
%dw 2.0 var myVar = "Some, Body" output application/json --- read(myVar,"application/csv",{header:false})[0]
1
{ "column_0": "Some", "column_1": " Body" }
Example
This example reads the specified XML and shows the syntax for a reader property,
in this case, { indexedReader: "false" }
.
1
2
3
4
5
6
7
8
%dw 2.0
output application/xml
---
{
"XML" : read("<prices><basic>9.99</basic></prices>",
"application/xml",
{ indexedReader: "false" })."prices"
}
1
2
3
4
<?xml version='1.0' encoding='UTF-8'?>
<XML>
<basic>9.99</basic>
</XML>
1.1.47. readUrl
readUrl(String, String, Object): Any
Similar to the read
function. However, readURL
accepts a URL, including
a classpath-based URL.
The classpath-based URL uses the classpath:`
protocol prefix, for example,
classpath://myfolder/myFile.txt
where myFolder
is located under
src/main/resources
in a Mule project. Otherwise, readURL
accepts
the same arguments as read
.
Parameters
Name | Description |
---|---|
|
The URL string to read. It also accepts a classpath-based URL. |
|
A supported format (or MIME type). Default: |
|
Optional: Sets reader configuration properties. For other formats and reader configuration properties, see DataWeave Output Formats and Writer Properties. |
Example
This example reads a JSON object from a URL. (For readability, the output
values shown below are shortened with …
.)
1
2
3
4
%dw 2.0
output application/json
---
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
1
{ "userId": 1, "id": 1, "title": "sunt aut ...", "body": "quia et ..." }
Example
This example reads a JSON object from a myJsonSnippet.json
file located in
the src/main/resources
directory in Studio. (Sample JSON content for that
file is shown in the Input section below.) After reading the file contents,
the script transforms selected fields from JSON to CSV. Reading files
in this way can be useful when trying out a DataWeave script on sample data,
especially when the source data is large and your script is complex.
1
2
3
4
5
%dw 2.0
var myJsonSnippet = readUrl("classpath://myJsonSnippet.json", "application/json")
output application/csv
---
(myJsonSnippet.results map(item) -> item.profile)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{
"results": [
{
"profile": {
"firstName": "john",
"lastName": "doe",
"email": "johndoe@demo.com"
},
"data": {
"interests": [
{
"language": "English",
"tags": [
"digital-strategy:Digital Strategy",
"innovation:Innovation"
],
"contenttypes": []
}
]
}
},
{
"profile": {
"firstName": "jane",
"lastName": "doe",
"email": "janedoe@demo.com"
},
"data": {
"interests": [
{
"language": "English",
"tags": [
"tax-reform:Tax Reform",
"retail-health:Retail Health"
],
"contenttypes": [
"News",
"Analysis",
"Case studies",
"Press releases"
]
}
]
}
}
]
}
1
2
3
firstName,lastName,email
john,doe,johndoe@demo.com
jane,doe,janedoe@demo.com
Example
This example reads a simple dwl
file from the src/main/resources
directory in Studio, then dynamically reads the value of the key name
from it. (Sample content for the input file is shown in the Input
section below.)
1
2
3
4
%dw 2.0
output application/json
---
(readUrl("classpath://name.dwl", "application/dw")).firstName
1
2
3
4
{
"firstName" : "Somebody",
"lastName" : "Special"
}
1
"Somebody"
1.1.48. reduce
reduce(Array<T>, (item: T, accumulator: T) → T): T | Null
Applies a reduction expression to the elements in an array.
For each element of the input array, in order, reduce
applies the reduction
lambda expression (function), then replaces the accumulator with the new
result. The lambda expression can use both the current input array element
and the current accumulator value.
Note that if the array is empty and no default value is set on the accumulator parameter, a null value is returned.
Parameters
Name | Description |
---|---|
|
Item in the input array. It provides the value to reduce. Can also be referenced as |
|
The accumulator. Can also be referenced as The accumulator parameter can be set to an initial value using the
syntax If an initial value for the accumulator is not set, the accumulator is set to the first element of the input array. Then the lambda expression is called with the second element of the input array. The initial value of the accumulator and the lambda expression
dictate the type of result produced by the |
Example
This example returns the sum of the numeric values in the first input array.
1
2
3
4
%dw 2.0
output application/json
---
[2, 3] reduce ($ + $$)
1
5
Example
This example adds the numbers in the sum
example, concatenates the same
numbers in concat
, and shows that an empty array []
(defined in
myEmptyList
) returns null
in emptyList
.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
var myNums = [1,2,3,4]
var myEmptyList = []
output application/json
---
{
"sum" : myNums reduce ($$ + $),
"concat" : myNums reduce ($$ ++ $),
"emptyList" : myEmptyList reduce ($$ ++ $)
}
1
{ "sum": 10, "concat": "1234", "emptyList": null }
Example
This example sets the first element from the first input array to "z"
, and
it adds 3
to the sum of the second input array. In multiply
, it shows how
to multiply each value in an array by the next
([2,3,3] reduce ((item, acc) → acc * item)
) to
produce a final result of 18
(= 2 * 3 * 3
). The final example,
multiplyAcc
, sets the accumulator to 3
to multiply the result of
acc * item
(= 12
) by 3
(that is, 3 (2 * 2 * 3) = 36
), as shown in
the output.
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
---
{
"concat" : ["a", "b", "c", "d"] reduce ((item, acc = "z") -> acc ++ item),
"sum": [0, 1, 2, 3, 4, 5] reduce ((item, acc = 3) -> acc + item),
"multiply" : [2,3,3] reduce ((item, acc) -> acc * item),
"multiplyAcc" : [2,2,3] reduce ((item, acc = 3) -> acc * item)
}
1
{ "concat": "zabcd", "sum": 18, "multiply": 18, "multiplyAcc": 36 }
Example
This example shows a variety of uses of reduce
, including its application to
arrays of boolean values and objects.
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
29
30
31
32
33
34
35
36
37
%dw 2.0
output application/json
var myVar =
{
"a": [0, 1, 2, 3, 4, 5],
"b": ["a", "b", "c", "d", "e"],
"c": [{ "letter": "a" }, { "letter": "b" }, { "letter": "c" }],
"d": [true, false, false, true, true]
}
---
{
"a" : [0, 1, 2, 3, 4, 5] reduce $$,
"b": ["a", "b", "c", "d", "e"] reduce $$,
"c": [{ "letter": "a" }, { "letter": "b" }, { "letter": "c" }] reduce ((item, acc = "z") -> acc ++ item.letter),
"d": [{ letter: "a" }, { letter: "b" }, { letter: "c" }] reduce $$,
"e": [true, false, false, true, true] reduce ($$ and $),
"f": [true, false, false, true, true] reduce ((item, acc) -> acc and item),
"g": [true, false, false, true, true] reduce ((item, acc = false) -> acc and item),
"h": [true, false, false, true, true] reduce $$,
"i": myVar.a reduce ($$ + $),
"j": myVar.a reduce ((item, acc) -> acc + item),
"k": myVar.a reduce ((item, acc = 3) -> acc + item),
"l": myVar.a reduce $$,
"m": myVar.b reduce ($$ ++ $),
"n": myVar.b reduce ((item, acc) -> acc ++ item),
"o": myVar.b reduce ((item, acc = "z") -> acc ++ item),
"p": myVar.b reduce $$,
"q": myVar.c reduce ((item, acc = "z") -> acc ++ item.letter),
"r": myVar.c reduce $$,
"s": myVar.d reduce ($$ and $),
"t": myVar.d reduce ((item, acc) -> acc and item),
"u": myVar.d reduce ((item, acc = false) -> acc and item),
"v": myVar.d reduce $$,
"w": ([0, 1, 2, 3, 4] reduce ((item, acc = {}) -> acc ++ { a: item })) pluck $,
"x": [] reduce $$,
"y": [] reduce ((item,acc = 0) -> acc + item)
}
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
"a": 0,
"b": "a",
"c": "zabc",
"d": { "letter": "a" },
"e": false,
"f": false,
"g": false,
"h": true,
"i": 15,
"j": 15,
"k": 18,
"l": 0,
"m": "abcde",
"n": "abcde",
"o": "zabcde",
"p": "a",
"q": "zabc",
"r": { "letter": "a" },
"s": false,
"t": false,
"u": false,
"v": true,
"w": [ 0,1,2,3,4 ],
"x": null,
"y": 0
}
reduce(Array<T>, (item: T, accumulator: A) → A): A
1.1.49. replace
replace(String, Regex): ((Array<String>, Number) → String) → String
Performs string replacement.
This version of replace
accepts a Java regular expression for matching
part of a string. It requires the use of the with
helper function to
specify a replacement string for the matching part of the input string.
Parameters
Name | Description |
---|---|
|
A string to match. |
|
A Java regular expression for matching characters in the input |
Example
The first example in the source replaces all characters up to and including
the second hyphen (123-456-
) with an empty value, so it returns the last
four digits. The second replaces the characters b13e
in the input string
with a hyphen (-
).
1
2
3
4
%dw 2.0
output application/json
---
["123-456-7890" replace /.*-/ with(""), "abc123def" replace /[b13e]/ with("-")]
1
[ 7890, "a-c-2-d-f" ]
Example
This example replaces the numbers 123
in the input strings with ID
. It
uses the regular expression (\d+)
, where the \d
metacharacter means any
digit from 0-9, and +
means that the digit can occur one or more times.
Without the +
, the output would contain one ID
per digit. The example
also shows how to write the expression using infix notation, then using
prefix notation.
1
2
3
4
%dw 2.0
output application/json
---
[ "my123" replace /(\d+)/ with("ID"), replace("myOther123", /(\d+)/) with("ID") ]
1
[ "myID", "myOtherID" ]
replace(String, String): ((Array<String>, Number) → String) → String
Performs string replacement.
This version of replace
accepts a string that matches part of a specified
string. It requires the use of the with
helper function to pass in a
replacement string for the matching part of the input string.
Parameters
Name | Description |
---|---|
|
The string to match. |
|
The string for matching characters in the input |
Example
This example replaces the numbers 123
from the input string with
the characters ID
, which are passed through the with
function.
1
2
3
4
%dw 2.0
output application/json
---
{ "replace": "admin123" replace "123" with("ID") }
1
{ "replace": "adminID" }
1.1.50. round
round(Number): Number
Rounds a number up or down to the nearest whole number.
Parameters
Name | Description |
---|---|
|
The number to evaluate. |
Parameters
Name | Description |
---|---|
|
The number to round. |
Example
This example rounds decimal numbers to the nearest whole numbers.
1
2
3
4
%dw 2.0
output application/json
---
[ round(1.2), round(4.6), round(3.5) ]
1
[ 1, 5, 4 ]
1.1.51. scan
scan(String, Regex): Array<Array<String>>
Returns an array with all of the matches found in an input string.
Each match is returned as an array that contains the complete match followed by any capture groups in your regular expression (if present).
Parameters
Name | Description |
---|---|
|
The input string to scan. |
|
A Java regular expression that describes the pattern match in
the |
Example
In this example, the regex
describes a URL. It contains three capture
groups within the parentheses, the characters before and after the period
(.
). It produces an array of matches to the input URL and the capture
groups. It uses flatten
to change the output from an array of arrays into
a simple array. Note that a regex
is specified within forward slashes (//
).
1
2
3
4
%dw 2.0
output application/json
---
flatten("www.mulesoft.com" scan(/([w]*).([a-z]*).([a-z]*)/))
1
[ "www.mulesoft.com", "www", "mulesoft", "com" ]
Example
In the example, the regex
describes an email address. It contains two
capture groups, the characters before and after the @
. It produces an
array matches to the email addresses and capture groups in the input string.
1
2
3
4
%dw 2.0
output application/json
---
"anypt@mulesoft.com,max@mulesoft.com" scan(/([a-z]*)@([a-z]*).com/)
1
2
3
4
[
[ "anypt@mulesoft.com", "anypt", "mulesoft" ],
[ "max@mulesoft.com", "max", "mulesoft" ]
]
1.1.52. sizeOf
sizeOf(Array<Any>): Number
Returns the number of elements in an array. It returns 0
if the array
is empty.
This version of sizeOf
takes an array or an array of arrays as input.
Other versions act on arrays of objects, strings, or binary values.
Parameters
Name | Description |
---|---|
|
The input array. The elements in the array can be any supported type. |
Example
This example counts the number of elements in the input array. It returns 3
.
1
2
3
4
%dw 2.0
output application/json
---
sizeOf([ "a", "b", "c"])
1
3
Example
This example returns a count of elements in the input array.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
---
{
"arraySizes": {
size3: sizeOf([1,2,3]),
size2: sizeOf([[1,2,3],[4]]),
size0: sizeOf([])
}
}
1
2
3
4
5
6
7
{
"arraySizes": {
"size3": 3,
"size2": 2,
"size0": 0
}
}
sizeOf(Object): Number
Returns the number of key-value pairs in an object.
This function accepts an array of objects. Returns 0
if the input object is
empty.
Parameters
Name | Description |
---|---|
|
The input object that contains one or more key-value pairs. |
Example
This example counts the key-value pairs in the input object, so it returns 2
.
1
2
3
4
%dw 2.0
output application/json
---
sizeOf({a: 1, b: 2})
1
2
Example
This example counts the key-value pairs in an object.
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
---
{
objectSizes : {
sizeIs2: sizeOf({a:1,b:2}),
sizeIs0: sizeOf({})
}
}
1
2
3
4
5
6
{
"objectSize": {
"sizeIs2": 2,
"sizeIs0": 0
}
}
sizeOf(Binary): Number
Returns the number of elements in an array of binary values.
Parameters
Name | Description |
---|---|
|
The input array of binary values. |
Example
This example returns the size of an array of binary values.
1
2
3
4
%dw 2.0
output application/json
---
sizeOf(["\u0000" as Binary, "\u0001" as Binary, "\u0002" as Binary])
1
3
sizeOf(String): Number
Returns the number of characters (including white space) in an string.
Returns 0
if the string is empty.
Parameters
Name | Description |
---|---|
|
The input text. |
Example
This example returns the number of characters in the input string "abc"
.
1
2
3
4
%dw 2.0
output application/json
---
sizeOf("abc")
1
3
Example
This example returns the number of characters in the input strings. Notice it
counts blank spaces in the string "my string"
and that
sizeOf("123" as Number)
returns 1
because 123
is coerced into a number,
so it is not a string.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
sizeOfSting2 : sizeOf("my string"),
sizeOfEmptyString: sizeOf(""),
sizeOfNumber : sizeOf("123" as Number)
}
1
2
3
4
5
{
"sizeOfSting2": 9,
"sizeOfEmptyString": 0,
"sizeOfNumber": 1
}
1.1.53. splitBy
splitBy(String, Regex): Array<String>
Splits a string into a string array based on a value that matches part of that string. It filters out the matching part from the returned array.
This version of splitBy
accepts a Java regular expression (regex) to
match the input string. The regex can match any character in the input
string. Note that splitBy
performs the opposite operation of joinBy
.
Parameters
Name | Description |
---|---|
|
The input string to split. |
|
A Java regular expression used to split the string. If it does not match some part of the string, the function will return the original, unsplit string in the array. |
Example
This example uses a Java regular expression to split an address block by the periods and forward slash in it. Notice that the regular expression goes between forward slashes.
1
2
3
4
%dw 2.0
output application/json
---
"192.88.99.0/24" splitBy(/[.\/]/)
1
["192", "88", "99", "0", "24"]
Example
This example uses several regular expressions to split input strings. The
first uses \/^*.b./\
to split the string by -b-
. The second uses /\s/
to split by a space. The third example returns the original input string in
an array ([ "no match"]
) because the regex /^s/
(for matching the first
character if it is s
) does not match the first character in the input
string ("no match"
). The fourth, which uses /^n../
, matches the first
characters in "no match"
, so it returns [ "", "match"]
. The last removes
all numbers and capital letters from a string, leaving each of the lower case
letters in the array. Notice that the separator is omitted from the output.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
output application/json
---
{ "splitters" : {
"split1" : "a-b-c" splitBy(/^*.b./),
"split2" : "hello world" splitBy(/\s/),
"split3" : "no match" splitBy(/^s/),
"split4" : "no match" splitBy(/^n../),
"split5" : "a1b2c3d4A1B2C3D" splitBy(/^*[0-9A-Z]/)
}
}
1
2
3
4
5
6
7
8
9
{
splitters: {
split1: [ "a", "c" ],
split2: [ "hello", "world" ],
split3: [ "no match" ],
split4: [ "", "match" ],
split5: [ "a", "b", "c", "d" ]
}
}
splitBy(String, String): Array<String>
Splits a string into a string array based on a separating string that matches part of the input string. It also filters out the matching string from the returned array.
The separator can match any character in the input. Note that splitBy
performs
the opposite operation of joinBy
.
Parameters
Name | Description |
---|---|
|
The string to split. |
|
A string used to separate the input string. If it does not match some part of the string, the function will return the original, unsplit string in the array. |
Example
This example splits a string containing an IP address by its periods.
1
2
3
4
%dw 2.0
output application/json
---
"192.88.99.0" splitBy(".")
1
["192", "88", "99", "0"]
Example
The first example (splitter1
) uses a hyphen (-
) in "a-b-c"
to split the
string. The second uses an empty string (""
) to split each character
(including the blank space) in the string. The third example splits based
on a comma (,
) in the input string. The last example does not split the
input because the function is case sensitive, so the upper case NO
does not
match the lower case no
in the input string. Notice that the separator is
omitted from the output.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
---
{ "splitters" : {
"split1" : "a-b-c" splitBy("-"),
"split2" : "hello world" splitBy(""),
"split3" : "first,middle,last" splitBy(","),
"split4" : "no split" splitBy("NO")
}
}
1
2
3
4
5
6
7
8
{
splitters: {
split1: [ "a","b","c" ],
split2: [ "h","e","l","l","o","","w","o","r","l","d" ],
split3: [ "first","middle","last"],
split4: [ "no split"]
}
}
1.1.54. sqrt
sqrt(Number): Number
Returns the square root of a number.
Parameters
Name | Description |
---|---|
|
The number to evaluate. |
Example
This example returns the square root of a number.
1
2
3
4
%dw 2.0
output application/json
---
[ sqrt(4), sqrt(25), sqrt(100) ]
1
[ 2.0, 5.0, 10.0 ]
1.1.55. startsWith
startsWith(String, String): Boolean
Returns true
or false
depending on whether the input string starts with a
matching prefix.
Parameters
Name | Description |
---|---|
|
The input string. |
|
A string that identifies the prefix. |
Example
This example indicates whether the strings start with a given prefix.
Note that you can use the startsWith(text,prefix)
or
text startsWith(prefix)
notation (for example,
startsWith("Mari","Mar")
or "Mari" startsWith("Mar")
).
1
2
3
4
%dw 2.0
output application/json
---
[ "Mari" startsWith("Mar"), "Mari" startsWith("Em") ]
1
[ true, false ]
1.1.56. sum
sum(Array<Number>): Number
Returns the sum of numeric values in an array.
Returns 0
if the array is empty and produces an error when non-numeric
values are in the array.
Parameters
Name | Description |
---|---|
|
The input array of numbers. |
Example
This example returns the sum of the values in the input array.
1
2
3
4
%dw 2.0
output application/json
---
sum([1, 2, 3])
1
6
1.1.57. to
to(Number, Number): Range
Returns a range with the specified boundaries.
The upper boundary is inclusive.
Parameters
Name | Description |
---|---|
|
A number ( |
|
A number ( |
Example
This example lists a range of numbers from 1 to 10.
1
2
3
4
%dw 2.0
output application/json
---
{ "myRange": 1 to 10 }
1
{ "myRange": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }
1.1.58. trim
trim(String): String
Removes any blank spaces from the beginning and end of a string.
Parameters
Name | Description |
---|---|
|
The string from which to remove any blank spaces. |
Example
This example trims a string. Notice that it does not remove any spaces from the middle of the string, only the beginning and end.
1
2
3
4
%dw 2.0
output application/json
---
{ "trim": trim(" my really long text ") }
1
{ "trim": "my really long text" }
Example
This example shows how trim
handles a variety strings and how it
handles a null value.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
---
{
"null": trim(null),
"empty": trim(""),
"blank": trim(" "),
"noBlankSpaces": trim("abc"),
"withSpaces": trim(" abc ")
}
1
2
3
4
5
6
7
{
"null": null,
"empty": "",
"blank": "",
"noBlankSpaces": "abc",
"withSpaces": "abc"
}
trim(Null): Null
Helper function that allows trim to work with null values.
1.1.59. typeOf
typeOf(T): Type<T>
Returns the type of a value.
Parameters
Name | Description |
---|---|
|
A string, object, array, number, or other supported type. |
Example
This example identifies the type of several input values.
1
2
3
4
%dw 2.0
output application/json
---
[ typeOf("A b"), typeOf([1,2]), typeOf(34), typeOf(true), typeOf({ a : 5 }) ]
1
[ "String", "Array", "Number", "Boolean", "Object" ]
1.1.60. unzip
unzip(Array<Array<T>>): Array<Array<T>>
Performs the opposite of zip
. It takes an array of arrays as input.
The function groups the values of the input sub-arrays by matching indices, and it outputs new sub-arrays with the values of those matching indices. No sub-arrays are produced for unmatching indices. For example, if one input sub-array contains four elements (indices 0-3) and another only contains three (indices 0-2), the function will not produce a sub-array for the value at index 3.
Parameters
Name | Description |
---|---|
|
The input array of arrays. |
Example
This example unzips an array of arrays. It outputs the first index of each
sub-array into one array [ 0, 1, 2, 3 ]
, and the second index of each into
another [ "a", "b", "c", "d" ]
.
1
2
3
4
%dw 2.0
output application/json
---
unzip([ [0,"a"], [1,"b"], [2,"c"],[ 3,"d"] ])
1
[ [ 0, 1, 2, 3 ], [ "a", "b", "c", "d" ] ]
Example
This example unzips an array of arrays. Notice that the number of elements in the input arrays is not all the same. The function creates only as many full sub-arrays as it can, in this case, just one.
1
2
3
4
%dw 2.0
output application/json
---
unzip([ [0,"a"], [1,"a","foo"], [2], [3,"a"] ])
1
[0,1,2,3]
1.1.61. upper
upper(String): String
Returns the provided string in uppercase characters.
Parameters
Name | Description |
---|---|
|
The string to convert to uppercase. |
Example
This example converts lowercase characters to uppercase.
1
2
3
4
%dw 2.0
output application/json
---
{ "name" : upper("mulesoft") }
1
{ "name": "MULESOFT" }
upper(Null): Null
Helper function that allows upper to work with null values.
1.1.62. uuid
uuid(): String
Returns a v4 UUID using random numbers as the source.
Example
This example generates a random v4 UUID.
%dw 2.0 output application/json --- uuid()
1
"7cc64d24-f2ad-4d43-8893-fa24a0789a99"
1.1.63. valuesOf
valuesOf({ (K)?: V }): Array<V>
Returns an array of the values from key-value pairs in an object.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
|
The object to evaluate. |
Example
This example returns the values from the input object.
1
2
3
4
%dw 2.0
output application/json
---
{ "valuesOf" : valuesOf({a: true, b: 1}) }
1
{ "valuesOf" : [true,1] }
1.1.64. with
with(((V, U) → R) → X, (V, U) → R): X
When used with replace
, with
passes a replacement string.
Parameters
Name | Description |
---|---|
|
The value to be replaced. |
|
The replacement value for the input value. |
Example
This example replaces all numbers in a string with "x" characters.
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.65. write
write(Any, String, Object): String | Binary
Writes a value as a string or binary in a supported format.
Returns a string or binary with the serialized representation of the value
in the specified format (MIME type). This function can write to a different
format than the input. Note that the data must validate in that new format,
or an error will occur. For example, application/xml
content is not valid
within an application/json
format, but text/plain
can be valid.
Parameters
Name | Description |
---|---|
|
The value to write. The value can be of any supported data type. |
|
A supported format (or MIME type) to write. Default: |
|
Optional: Sets writer configuration properties. For writer configuration properties (and other supported MIME types), see DataWeave Output Formats and Writer Properties. |
Example
This example writes the string world
in plain text (text/plain"
). It
outputs that string as the value of a JSON object with the key hello
.
1
2
3
4
%dw 2.0
output application/json
---
{ hello : write("world", "text/plain") }
1
{ "hello": "world" }
Example
This example takes JSON input and writes the payload to a CSV format that uses a
pipe (|
) separator and includes the header (matching keys in the JSON objects).
Note that if you instead use "header":false
in your script, the output will
lack the Name|Email|Id|Title
header in the output.
1
2
3
4
%dw 2.0
output application/xml
---
{ "output" : write(payload, "application/csv", {"header":true, "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.66. xsiType
xsiType(String, Namespace)
Creates a xsi:type
type attribute. This method returns an object, so it must be used with dynamic attributes.
Introduced in DataWeave 2.2.2. Supported by Mule 4.2.2 and later.
Parameters
Name | Description |
---|---|
|
The name of the schema |
|
The namespace of that type. |
Example
This example shows how the xsiType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/xml
ns acme http://acme.com
---
{
user @((xsiType("user", acme))): {
name: "Peter",
lastName: "Parker"
}
}
1
2
3
4
5
<?xml version='1.0' encoding='UTF-8'?>
<user xsi:type="acme:user" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:acme="http://acme.com">
<name>Peter</name>
<lastName>Parker</lastName>
</user>
1.1.67. zip
zip(Array<T>, Array<R>): Array<Array<T | R>>
Merges elements from two arrays into an array of arrays.
The first sub-array in the output array contains the first indices of the input sub-arrays. The second index contains the second indices of the inputs, the third contains the third indices, and so on for every case where there are the same number of indices in the arrays.
Parameters
Name | Description |
---|---|
|
The array on the left-hand side of the function. |
|
The array on the right-hand side of the function. |
Example
This example zips the arrays located to the left and right of zip
. Notice
that it returns an array of arrays where the first index, ([0,1]
) contains
the first indices of the specified arrays. The second index of the output array
([1,"b"]
) contains the second indices of the specified arrays.
1
2
3
4
%dw 2.0
output application/json
---
[0,1] zip ["a","b"]
1
[ [0,"a"], [1,"b"] ]
Example
This example zips elements of the left-hand and right-hand arrays. Notice that only elements with counterparts at the same index are returned in the array.
1
2
3
4
5
6
7
8
9
%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"],
"d" : [0, 1, 2] zip ["a", "b", "c", "d"]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"a": [
[0,"a"],
[1,"b"],
[2,"c"],
[3,"d"]
],
"b": [
[0,"a"]
],
"c": [
[0,"a"],
[1,"b"]
],
"d": [
[0,"a"],
[1,"b"],
[2,"c"]
]
}
Example
This example zips more than two arrays. Notice that items from
["aA", "bB"]
in list4
are not in the output because the other input
arrays only have two indices.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
var myvar = {
"list1": ["a", "b"],
"list2": [1, 2, 3],
"list3": ["aa", "bb"],
"list4": [["A", "B", "C"], [11, 12], ["aA", "bB"]]
}
---
((myvar.list1 zip myvar.list2) zip myvar.list3) zip myvar.list4
1
2
3
4
5
6
7
8
[
[
[ [ "a", 1 ], "aa" ], [ "A", "B", "C" ]
],
[
[ [ "b", 2 ], "bb" ], [ 11, 12 ]
]
]
1.2. Types
1.2.1. Any
The top-level type. Any
extends all of the system types, which
means that anything can be assigned to a Any
typed variable.
1
Any
1.2.2. Array
Array type that requires a Type(T)
to represent the elements of the list.
Example: Array<Number>
represents an array of numbers, and Array<Any>
represents an array of any type.
Example: [1, 2, "a", "b", true, false, { a : "b"}, [1, 2, 3] ]
1
Array
1.2.3. Binary
A blob.
1
Binary
1.2.4. Boolean
A Boolean
type of true
or false
.
1
Boolean
1.2.5. CData
XML defines a CData
custom type 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 string arrives inside a CDATA block. CData
inherits
from the type String
.
Source:
output application/xml --- { "user" : "Shoki" as CData }
Output:
<?xml version="1.0" encoding="UTF-8"?><user><![CDATA[Shoki]]></user>
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 a year, month, and day. For example: |2018-09-17|
1
Date
1.2.8. DateTime
A Date
and Time
within a TimeZone
. For example: |2018-09-17T22:13:00Z|
1
DateTime
1.2.9. Dictionary
Generic dictionary interface.
1
{ _?: T }
1.2.10. Enum
This type is based on 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.
Source:
"Max" as Enum {class: "com.acme.MuleyEnum"}
1
String {enumeration: true}
1.2.11. Iterator
This type is based on the iterator Java class. The iterator contains a collection and includes methods to iterate through and filter it.
Just like the Java class, Iterator
is designed to be consumed only once. For
example, if you pass it to a
Logger component,
the Logger consumes it, so it becomes unreadable by further elements in the flow.
1
Array {iterator: true}
1.2.12. Key
A key of an Object
.
Examples: { myKey : "a value" }
, { myKey : { a : 1, b : 2} }
,
{ myKey : [1,2,3,4] }
1
Key
1.2.13. LocalDateTime
A DateTime
in the current TimeZone
. For example: |2018-09-17T22:13:00|
1
LocalDateTime
1.2.14. LocalTime
A Time
in the current TimeZone
. For example: |22:10:18|
1
LocalTime
1.2.15. NaN
java.lang.Float
and java.lang.Double
have special cases for NaN
and Infinit
.
DataWeave does not have these concepts for its number multi-precision nature.
So when it is mapped to DataWeave values, it is wrapped in a Null with a Schema marker.
1
Null {NaN: true}
1.2.16. Namespace
A Namespace
type represented by a URI
and a prefix.
1
Namespace
1.2.17. Nothing
Bottom type. This type can be assigned to all the types.
1
Nothing
1.2.18. Null
A Null type.
1
Null
1.2.19. Number
A number type: Any number, decimal, or integer is represented by the Number` type.
1
Number
1.2.20. Object
Type that represents any object, which is a collection of Key
and value pairs.
Examples: { myKey : "a value" }
, { myKey : { a : 1, b : 2} }
,
{ myKey : [1,2,3,4] }
1
Object
1.2.21. Pair
A type used to represent a pair of values.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
1
{ l: LEFT, r: RIGHT }
1.2.22. Period
A period.
1
Period
1.2.23. Range
A Range
type represents a sequence of numbers.
1
Range
1.2.24. Regex
A Java regular expression (regex) type.
1
Regex
1.2.25. SimpleType
A union type that represents all the simple types.
1
String | Boolean | Number | DateTime | LocalDateTime | Date | LocalTime | Time | TimeZone | Period
1.2.26. String
String
type
1
String
1.2.27. StringCoerceable
A union type of all the types that can be coerced to String type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
1
String | Boolean | Number | DateTime | LocalDateTime | Date | LocalTime | Time | TimeZone | Period | Key | Binary | Uri | Type<Any> | Regex | Namespace
1.2.28. Time
A time in a specific TimeZone
. For example: |22:10:18Z|
1
Time
1.2.29. TimeZone
A time zone.
1
TimeZone
1.2.30. Type
A type in the DataWeave type system.
1
Type
1.2.31. Uri
A URI.
1
Uri
1.3. Annotations
1.4. Namespaces
1.4.1. xsi = http://www.w3.org/2001/XMLSchema-instance
Namespace declaration of XMLSchema.
2. dw::Crypto
This module provide functions that perform encryptions through common algorithms, such as MD5, SHA1, and so on.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::Crypto
to the header of your
DataWeave script.
2.1. Functions
2.1.1. HMACBinary
HMACBinary(Binary, Binary, String): Binary
Computes an HMAC hash (with a secret cryptographic key) on input content.
See also, HMACWith
.
Parameters
Name | Description |
---|---|
|
The secret cryptographic key (a |
|
The input content, a |
|
The hashing algorithm. By default HmacSHA1 is used. |
Example
This example uses HMAC with a secret value to encrypt the input content.
1
2
3
4
5
%dw 2.0
import dw::Crypto
output application/json
---
{ "HMACBinary" : Crypto::HMACBinary("key_re_loca" as Binary, "xxxxx" as Binary) }
1
{ "HMACBinary": ".-\ufffd\ufffd\u0012\ufffdÛŠ\ufffd\ufffd\u0000\ufffd\u0012\u0018R\ufffd\ufffd=\ufffd*" }
2.1.2. HMACWith
HMACWith(Binary, Binary, String): String
Computes an HMAC hash (with a secret cryptographic key) on input content, then transforms the result into a lowercase, hexadecimal string.
See also, HMACBinary
.
Parameters
Name | Description |
---|---|
|
The secret cryptographic key (a |
|
The input content, a |
|
(Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.) The hashing algorithm. By default, |
Example
This example uses HMAC with a secret value to encrypt the input content using the HmacSHA256
algorithm.
1
2
3
4
5
%dw 2.0
import dw::Crypto
output application/json
---
{ "HMACWith" : Crypto::HMACWith("secret_key" as Binary, "Some value to hash" as Binary, "HmacSHA256") }
1
{ "HMACWith": "b51b4fe8c4e37304605753272b5b4321f9644a9b09cb1179d7016c25041d1747" }
2.1.3. MD5
MD5(Binary): String
Computes the MD5 hash and transforms the binary result into a hexadecimal lower case string.
Parameters
Name | Description |
---|---|
|
A binary input value to encrypt. |
Example
This example uses the MD5 algorithm to encrypt a binary value.
1
2
3
4
5
%dw 2.0
import dw::Crypto
output application/json
---
{ "md5" : Crypto::MD5("asd" as Binary) }
1
{ "md5": "7815696ecbf1c96e6894b779456d330e" }
2.1.4. SHA1
SHA1(Binary): String
Computes the SHA1 hash and transforms the result into a hexadecimal, lowercase string.
Parameters
Name | Description |
---|---|
|
A binary input value to encrypt. |
Example
This example uses the SHA1 algorithm to encrypt a binary value.
1
2
3
4
5
%dw 2.0
import dw::Crypto
output application/json
---
{ "sha1" : Crypto::SHA1("dsasd" as Binary) }
1
{ "sha1": "2fa183839c954e6366c206367c9be5864e4f4a65" }
2.1.5. hashWith
hashWith(Binary, String): Binary
Computes the hash value of binary content using a specified algorithm.
The first argument specifies the binary content to use to calculate the hash value, and the second argument specifies the hashing algorithm to use. The second argument must be any of the accepted Algorithm names:
Algorithm names | Description |
---|---|
|
The MD2 message digest algorithm as defined in RFC 1319[http://www.ietf.org/rfc/rfc1319.txt]. |
|
The MD5 message digest algorithm as defined in RFC 1321[http://www.ietf.org/rfc/rfc1321.txt]. |
|
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. |
Parameters
Name | Description |
---|---|
|
The binary input content to hash. |
|
The name of the algorithm to use to calculate the hash value of |
Example
This example uses the MD2 algorithm to encrypt a binary value.
1
2
3
4
5
%dw 2.0
import dw::Crypto
output application/json
---
{ "md2" : Crypto::hashWith("hello" as Binary, "MD2") }
1
{ "md2": "\ufffd\u0004ls\ufffd\u00031\ufffdh\ufffd}8\u0004\ufffd\u0006U" }
3. dw::Runtime
This module contains functions that allow you to interact with the DataWeave engine.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::Runtime
to the header of your
DataWeave script.
3.1. Functions
3.1.1. fail
fail(String): Nothing
Throws an exception with the specified message.
Parameters
Name | Description |
---|---|
|
An error message ( |
Example
This example returns a failure message Data was empty
because the expression
(sizeOf(myVar) <= 0)
is true
. A shortened version of the error message
is shown in the Output section below.
1
2
3
4
5
6
%dw 2.0
import * from dw::Runtime
var result = []
output application/json
---
if(sizeOf(result) <= 0) fail('Data was empty') else result
1
2
3
4
ERROR 2018-07-29 11:47:44,983 ...
*********************************
Message : "Data was empty
...
3.1.2. failIf
failIf(T, (value: T) → Boolean, String): T
Produces an error with the specified message if the expression in
the evaluator returns true
, otherwise returns the value.
Parameters
Name | Description |
---|---|
|
The value to return only if the |
|
Expression that returns |
Example
This example produces a runtime error (instead of a SUCCESS message) because
the expression isEmpty(result)
is true
. It is true
because an empty
object is passed through variable result
.
1
2
3
4
5
6
%dw 2.0
import failIf from dw::Runtime
var result = {}
output application/json
---
{ "result" : "SUCCESS" failIf (isEmpty(result)) }
1
2
3
ERROR 2018-07-29 11:56:39,988 ...
**********************************
Message : "Failed
3.1.3. locationString
locationString(Any): String
Returns the location string of a given value.
Parameters
Name | Description |
---|---|
|
A value of any type. |
Example
This example returns the contents of the line (the location) that defines
variable a
in the header of the DataWeave script.
1
2
3
4
5
6
%dw 2.0
import * from dw::Runtime
var a = 123
output application/json
---
locationString(a)
1
"var a = 123"
3.1.4. orElse
orElse(TryResult<T>, () → R): T | R
Returns the result of the orElse
if the previous
try result failed if not returns the result of the previous
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
Previous try result |
|
The next option to try if the previous fails |
Example
This example waits shows how to chain different try
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::Runtime
var user = {}
var otherUser = {name: "DW"}
output application/json
---
{
a: try(() -> user.name!) orElse "No User Name",
b: try(() -> otherUser.name) orElse "No User Name"
}
1
2
3
4
{
"a": "No User Name",
"b": "DW"
}
3.1.5. orElseTry
orElseTry(TryResult<T>, () → R): TryResult<T | R>
Function to be use with try in order to chain multiple try
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
Previous try result |
|
The next option to try if the previous fails |
Example
This example waits shows how to chain different try
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::Runtime
var user = {}
var otherUser = {}
output application/json
---
{
a: try(() -> user.name!) orElseTry otherUser.name!,
b: try(() -> user.name!) orElseTry "No User Name"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"a": {
"success": false,
"error": {
"kind": "KeyNotFoundException",
"message": "There is no key named 'name'",
"location": "\n9| a: try(() -> user.name!) orElseTry otherUser.name!,\n ^^^^^^^^^^^^^^",
"stack": [
"main (org::mule::weave::v2::engine::transform:9:40)"
]
}
},
"b": {
"success": true,
"result": "No User Name"
}
}
3.1.6. prop
prop(String): String | Null
Returns the value of the property with the specified name or null
if the
property is not defined.
Parameters
Name | Description |
---|---|
|
The property to retrieve. |
Example
This example gets the user.timezone
property.
1
2
3
4
5
%dw 2.0
import * from dw::Runtime
output application/dw
---
{ "props" : prop("user.timezone") }
1
{ props: "America/Los_Angeles" as String {class: "java.lang.String"} }
3.1.7. props
props(): Dictionary<String>
Returns all the properties configured for Mule runtime.
Example
This example returns all properties from the java.util.Properties
class.
1
2
3
4
5
%dw 2.0
import * from dw::Runtime
output application/dw
---
{ "props" : props() }
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
{
props: {
"java.vendor": "Oracle Corporation" as String {class: "java.lang.String"},
"sun.java.launcher": "SUN_STANDARD" as String {class: "java.lang.String"},
"sun.management.compiler": "HotSpot 64-Bit Tiered Compilers" as String ..., * "os.name": "Mac OS X" as String {class: "java.lang.String"},
"sun.boot.class.path": "/Library/Java/JavaVirtualMachines/ ...,
"org.glassfish.grizzly.nio.transport.TCPNIOTransport...": "1048576" ...,
"java.vm.specification.vendor": "Oracle Corporation" as String ...,
"java.runtime.version": "1.8.0_111-b14" as String {class: "java.lang.String"},
"wrapper.native_library": "wrapper" as String {class: "java.lang.String"},
"wrapper.key": "XlIl4YartmfEU3oKu7o81kNQbwhveXi-" as String ...,
"user.name": "me" as String {class: "java.lang.String"},
"mvel2.disable.jit": "TRUE" as String {class: "java.lang.String"},
"user.language": "en" as String {class: "java.lang.String"} ...,
"sun.boot.library.path": "/Library/Java/JavaVirtualMachines ...
"xpath.provider": "com.mulesoft.licm.DefaultXPathProvider" ...,
"wrapper.backend": "pipe" as String {class: "java.lang.String"},
"java.version": "1.8.0_111" as String {class: "java.lang.String"},
"user.timezone": "America/Los_Angeles" as String {class: "java.lang.String"},
"java.net.preferIPv4Stack": "TRUE" as String {class: "java.lang.String"},
"sun.arch.data.model": "64" as String {class: "java.lang.String"},
"java.endorsed.dirs": "/Library/Java/JavaVirtualMachines/...,
"sun.cpu.isalist": "" as String {class: "java.lang.String"},
"sun.jnu.encoding": "UTF-8" as String {class: "java.lang.String"},
"mule.testingMode": "" as String {class: "java.lang.String"},
"file.encoding.pkg": "sun.io" as String {class: "java.lang.String"},
"file.separator": "/" as String {class: "java.lang.String"},
"java.specification.name": "Java Platform API Specification" ...,
"java.class.version": "52.0" as String {class: "java.lang.String"},
"jetty.git.hash": "82b8fb23f757335bb3329d540ce37a2a2615f0a8" ...,
"user.country": "US" as String {class: "java.lang.String"},
"mule.agent.configuration.folder": "/Applications/AnypointStudio.app/ ...,
"log4j.configurationFactory": "org.apache.logging.log4j.core...",
"java.home": "/Library/Java/JavaVirtualMachines/...,
"java.vm.info": "mixed mode" as String {class: "java.lang.String"},
"wrapper.version": "3.5.34-st" as String {class: "java.lang.String"},
"os.version": "10.13.4" as String {class: "java.lang.String"},
"org.eclipse.jetty.LEVEL": "WARN" as String {class: "java.lang.String"},
"path.separator": ":" as String {class: "java.lang.String"},
"java.vm.version": "25.111-b14" as String {class: "java.lang.String"},
"wrapper.pid": "5212" as String {class: "java.lang.String"},
"java.util.prefs.PreferencesFactory": "com.mulesoft.licm..."},
"wrapper.java.pid": "5213" as String {class: "java.lang.String"},
"mule.home": "/Applications/AnypointStudio.app/...,
"java.awt.printerjob": "sun.lwawt.macosx.CPrinterJob" ...,
"sun.io.unicode.encoding": "UnicodeBig" as String {class: "java.lang.String"},
"awt.toolkit": "sun.lwawt.macosx.LWCToolkit" ...,
"org.glassfish.grizzly.nio.transport...": "1048576" ...,
"user.home": "/Users/me" as String {class: "java.lang.String"},
"java.specification.vendor": "Oracle Corporation" ...,
"java.library.path": "/Applications/AnypointStudio.app/...,
"java.vendor.url": "http://java.oracle.com/" as String ...,
"java.vm.vendor": "Oracle Corporation" as String {class: "java.lang.String"},
gopherProxySet: "false" as String {class: "java.lang.String"},
"wrapper.jvmid": "1" as String {class: "java.lang.String"},
"java.runtime.name": "Java(TM) SE Runtime Environment" ...,
"mule.encoding": "UTF-8" as String {class: "java.lang.String"},
"sun.java.command": "org.mule.runtime.module.reboot....",
"java.class.path": "%MULE_LIB%:/Applications/AnypointStudio.app...",
"log4j2.loggerContextFactory": "org.mule.runtime.module.launcher...,
"java.vm.specification.name": "Java Virtual Machine Specification" ,
"java.vm.specification.version": "1.8" as String {class: "java.lang.String"},
"sun.cpu.endian": "little" as String {class: "java.lang.String"},
"sun.os.patch.level": "unknown" as String {class: "java.lang.String"},
"com.ning.http.client.AsyncHttpClientConfig.useProxyProperties": "true" ...,
"wrapper.cpu.timeout": "10" as String {class: "java.lang.String"},
"java.io.tmpdir": "/var/folders/42/dd73l3rx7qz0n625hr29kty80000gn/T/" ...,
"anypoint.platform.analytics_base_uri": ...,
"java.vendor.url.bug": "http://bugreport.sun.com/bugreport/" ...,
"os.arch": "x86_64" as String {class: "java.lang.String"},
"java.awt.graphicsenv": "sun.awt.CGraphicsEnvironment" ...,
"mule.base": "/Applications/AnypointStudio.app...",
"java.ext.dirs": "/Users/staceyduke/Library/Java/Extensions: ..."},
"user.dir": "/Applications/AnypointStudio.app/..."},
"line.separator": "\n" as String {class: "java.lang.String"},
"java.vm.name": "Java HotSpot(TM) 64-Bit Server VM" ...,
"org.quartz.scheduler.skipUpdateCheck": "true" ...,
"file.encoding": "UTF-8" as String {class: "java.lang.String"},
"mule.forceConsoleLog": "" as String {class: "java.lang.String"},
"java.specification.version": "1.8" as String {class: "java.lang.String"},
"wrapper.arch": "universal" as String {class: "java.lang.String"}
} as Object {class: "java.util.Properties"}
3.1.8. try
try(() → T): TryResult<T>
Evaluates the delegate function and returns an object with success: true
and result
if the delegate function succeeds, or an object with success: false
and error
if the delegate function throws an exception.
Parameters
Name | Description |
---|---|
|
The function to evaluate. |
Example
This example calls the try
function using the randomNumber
function as argument.
The function randomNumber
generates a random number and calls fail
if the number is higher than 0.5. The declaration of this function is in the script’s header.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import try, fail from dw::Runtime
output application/json
fun randomNumber() =
if(random() > 0.5)
fail("This function is failing")
else
"OK"
---
try(() -> randomNumber())
When randomNumber
fails, the output is:
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"success": false,
"error": {
"kind": "UserException",
"message": "This function is failing",
"location": "Unknown location",
"stack": [
"fail (anonymous:0:0)",
"myFunction (anonymous:1:114)",
"main (anonymous:1:179)"
]
}
}
When randomNumber
succeeds, the output is:
1
2
3
4
{
"success": true,
"result": "OK"
}
Based on the output of the try
function, you can add conditional logic to execute when the result is success: true
or success: false
.
3.1.9. wait
wait(T, Number): T
Stops the execution for the specified timeout (in milliseconds).
Stopping the execution will block the thread used, potentially causing slowness, low performance and potentially freezes of the entire runtime. This operation is intented for limited functional testing purposes and should not be used in production application, performance testing or with multiple applications deployed. |
Parameters
Name | Description |
---|---|
|
Input of any type. |
|
The number of milliseconds to wait. |
Example
This example waits 2000 milliseconds (2 seconds) to execute.
1
2
3
4
5
%dw 2.0
import * from dw::Runtime
output application/json
---
{ "user" : 1 } wait 2000
1
{ "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
This module contains functions that allow you to interact with the underlying system.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::System
to the header of your
DataWeave script.
4.1. Functions
4.1.1. envVar
envVar(String): String | Null
Returns an environment variable with the specified name or null
if the
environment variable is not defined.
Parameters
Name | Description |
---|---|
|
Provides the name of the environment variable. |
Example
This example returns a Mac command console (SHELL
) path and returns null
on FAKE_ENV_VAR
(an undefined environment variable). SHELL
is one of the
standard Mac environment variables. Also notice that the import
command
enables you to call the function without prepending the module name to it.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::System
output application/json
---
{
"envVars" : [
"real" : envVar("SHELL"),
"fake" : envVar("FAKE_ENV_VAR")
]
}
1
2
3
4
5
6
7
8
"envVars": [
{
"real": "/bin/bash"
},
{
"fake": null
}
]
4.1.2. envVars
envVars(): Dictionary<String>
Returns all of the environment variables defined in the host system.
Example
This example returns a Mac command console (SHELL
) path. SHELL
is one of
the standard Mac environment variables. To return all the environment
variables, you can use dw::System::envVars()
.
1
2
3
4
5
%dw 2.0
import dw::System
output application/json
---
{ "envVars" : dw::System::envVars().SHELL }
1
{ "envVars": "/bin/bash" }
5. dw::core::Arrays
This module contains helper functions for working with arrays.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Arrays
to the header of your
DataWeave script.
5.1. Functions
5.1.1. countBy
countBy(Array<T>, (T) → Boolean): Number
Counts the elements in an array that match the results of a function.
Parameters
Name | Description |
---|---|
|
The input array that contains elements to match. |
|
A function to apply to elements in the input array. |
Example
This counts the values in the array that are equal to the result of the
matchingFunction
((($ mod 2) == 0)
).
1
2
3
4
5
%dw 2.0
import * from dw::core::Arrays
output application/json
---
{ "countBy" : [1, 2, 3, 4] countBy (($ mod 2) == 0) }
1
{ "countBy": 2 }
5.1.2. divideBy
divideBy(Array<T>, Number): Array<Array<T>>
Breaks up an array into sub-arrays that contain the specified number of elements.
When there are fewer elements in the input array than the specified number, the function fills the sub-array with those elements. When there are more elements, the function fills as many sub-arrays needed with the extra elements.
Parameters
Name | Description |
---|---|
|
Items in the input array. |
|
The number of elements allowed per sub-array. |
Example
This example breaks up arrays into sub-arrays based on the specified amount
.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Arrays
output application/json
---
{
"divideBy" : [
{ "divideBy2" : [1, 2, 3, 4, 5] divideBy 2 },
{ "divideBy2" : [1, 2, 3, 4, 5, 6] divideBy 2 },
{ "divideBy3" : [1, 2, 3, 4, 5] divideBy 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
{
"divideBy": [
{
"divideBy2": [
[ 1, 2 ],
[ 3, 4 ],
[ 5 ]
]
},
{
"divideBy2": [
[ 1, 2 ],
[ 3, 4 ],
[ 5, 6 ]
]
},
{
"divideBy3": [
[ 1, 2, 3 ],
[ 4, 5 ]
]
}
]
}
5.1.3. drop
drop(Array<T>, Number): Array<T>
Drops the first n
elements. It returns the original array when n <= 0
and an empty array when n > sizeOf(array)
.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The left array of elements. |
|
The number of elements to take. |
Example
This example returns an array that only contains the third element of the input array. It drops the first two elements from the output.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
var users = ["Mariano", "Leandro", "Julian"]
output application/json
---
drop(users, 2)
1
2
3
[
"Julian"
]
5.1.4. dropWhile
dropWhile(Array<T>, (item: T) → Boolean): Array<T>
Drops elements from the array while the condition is met but stops the selection process when it reaches an element that fails to satisfy the condition.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The array of elements. |
|
The condition (or expression) used to match an element in the array. |
Example
This example returns an array that omits elements that are less then or equal to 2. It stops dropping elements when it reaches one that is greater than 2.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,3,4,1]
---
arr dropWhile $ <= 2
1
2
3
4
5
[
3,
4,
1
]
5.1.5. every
every(Array<T>, (T) → Boolean): Boolean
Returns true
if every element in the array matches the condition.
The function stops iterating after the first negative evaluation of an element in the array.
Parameters
Name | Description |
---|---|
|
The input array. |
|
A condition (or expression) to apply to elements in the input array. |
Example
This example applies a variety of expressions to the input arrays. The $
references values of the elements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
%dw 2.0
import * from dw::core::Arrays
var arr0 = [] as Array<Number>
output application/json
---
{ "results" : [
"ok" : [
[1,1,1] every ($ == 1),
[1] every ($ == 1)
],
"err" : [
[1,2,3] every ((log('should stop at 2 ==', $) mod 2) == 1),
[1,1,0] every ($ == 1),
[0,1,1,0] every (log('should stop at 0 ==', $) == 1),
[1,2,3] every ($ == 1),
arr0 every true,
]
]
}
1
2
3
4
5
6
7
8
9
10
{
"results": [
{
"ok": [ true, true ]
},
{
"err": [ false, false, false, false, false ]
}
]
}
every(Null, (Nothing) → Boolean): Boolean
Helper function to make every
work with a null
value.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
5.1.6. firstWith
firstWith(Array<T>, (item: T, index: Number) → Boolean): T | Null
Returns the first element that satisfy the condition or null y non element match.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
array |
The array of elements in where to search |
condition |
The condition that must be satisfy |
Example
This example shows how the firstWith
behaves when an elements matches and when it doesn’t
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
---
import firstWith from dw::core::Arrays
var users = [{name: "Mariano", lastName: "Achaval"}, {name: "Ana", lastName: "Felisatti"}, {name: "Mariano", lastName: "de Sousa"}]
---
{
a: users firstWith ((user, index) -> user.name == "Mariano"),
b: users firstWith ((user, index) -> user.name == "Peter")
}
1
2
3
4
5
6
7
{
"a": {
"name": "Mariano",
"lastName": "Achaval"
},
"b": null
}
5.1.7. indexOf
indexOf(Array<T>, T): Number
Returns the index of the first occurrence of an element within the array.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The array of elements. |
|
The element to find. |
Example
This example returns the index of the matching value from the input array.
The index of "Julian"
is 2
.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var users = ["Mariano", "Leandro", "Julian"]
---
indexOf(users, "Julian")
1
2
5.1.8. indexWhere
indexWhere(Array<T>, (item: T) → Boolean): Number
Returns the index of the first occurrence of an element that matches a condition within the array.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The array of elements. |
|
The condition (or expression) used to match an element in the array. |
Example
This example returns the index of the value from the input array that
matches the condition in the lambda expression,
(item) → item startsWith "Jul"
.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var users = ["Mariano", "Leandro", "Julian"]
---
users indexWhere (item) -> item startsWith "Jul"
1
2
5.1.9. join
join(Array<L>, Array<R>, (leftValue: L) → String, (rightValue: R) → String): Array<Pair<L, R>>
Joins two arrays of objects by a given ID criteria.
join
returns an array all the left
items, merged by ID with any
right items that exist.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The left-side array of objects. |
|
The right-side array of objects. |
|
The criteria used to extract the ID for the left collection. |
|
The criteria used to extract the ID for the right collection. |
Example
This example shows how join behaves. Notice that the output only includes
objects where the values of the input user.id
and product.ownerId
match.
The function includes the "l"
and "r"
keys in the output.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Arrays
var users = [{id: "1", name:"Mariano"},{id: "2", name:"Leandro"},{id: "3", name:"Julian"},{id: "5", name:"Julian"}]
var products = [{ownerId: "1", name:"DataWeave"},{ownerId: "1", name:"BAT"}, {ownerId: "3", name:"DataSense"}, {ownerId: "4", name:"SmartConnectors"}]
output application/json
---
join(users, products, (user) -> user.id, (product) -> product.ownerId)
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
29
30
31
32
[
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "DataWeave"
}
},
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "BAT"
}
},
{
"l": {
"id": "3",
"name": "Julian"
},
"r": {
"ownerId": "3",
"name": "DataSense"
}
}
]
5.1.10. leftJoin
leftJoin(Array<L>, Array<R>, (leftValue: L) → String, (rightValue: R) → String): Array<{ l: L, r?: R }>
Joins two arrays of objects by a given ID criteria.
leftJoin
returns an array all the left
items, merged by ID with any right
items that meet the joining criteria.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The left-side array of objects. |
|
The right-side array of objects. |
|
The criteria used to extract the ID for the left collection. |
|
The criteria used to extract the ID for the right collection. |
Example
This example shows how join behaves. Notice that it returns all objects from
the left-side array (left
) but only joins items from the right-side array
(right
) if the values of the left-side user.id
and right-side
product.ownerId
match.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Arrays
var users = [{id: "1", name:"Mariano"},{id: "2", name:"Leandro"},{id: "3", name:"Julian"},{id: "5", name:"Julian"}]
var products = [{ownerId: "1", name:"DataWeave"},{ownerId: "1", name:"BAT"}, {ownerId: "3", name:"DataSense"}, {ownerId: "4", name:"SmartConnectors"}]
output application/json
---
leftJoin(users, products, (user) -> user.id, (product) -> product.ownerId)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
[
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "DataWeave"
}
},
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "BAT"
}
},
{
"l": {
"id": "2",
"name": "Leandro"
}
},
{
"l": {
"id": "3",
"name": "Julian"
},
"r": {
"ownerId": "3",
"name": "DataSense"
}
},
{
"l": {
"id": "5",
"name": "Julian"
}
}
]
5.1.11. outerJoin
outerJoin(Array<L>, Array<R>, (leftValue: L) → String, (rightValue: R) → String): Array<{ l?: L, r?: R }>
Joins two array of objects by a given ID
criteria.
outerJoin
returns an array with all the left
items, merged by ID
with the right
items in cases where any exist, and it returns right
items that are not present in the left
.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The left-side array of objects. |
|
The right-side array of objects. |
|
The criteria used to extract the ID for the left collection. |
|
The criteria used to extract the ID for the right collection. |
Example
This example shows how join behaves. Notice that the output includes
objects where the values of the input user.id
and product.ownerId
match,
and it includes objects where there is no match for the value of the
user.id
or product.ownerId
.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Arrays
var users = [{id: "1", name:"Mariano"},{id: "2", name:"Leandro"},{id: "3", name:"Julian"},{id: "5", name:"Julian"}]
var products = [{ownerId: "1", name:"DataWeave"},{ownerId: "1", name:"BAT"}, {ownerId: "3", name:"DataSense"}, {ownerId: "4", name:"SmartConnectors"}]
output application/json
---
outerJoin(users, products, (user) -> user.id, (product) -> product.ownerId)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
[
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "DataWeave"
}
},
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "BAT"
}
},
{
"l": {
"id": "2",
"name": "Leandro"
}
},
{
"l": {
"id": "3",
"name": "Julian"
},
"r": {
"ownerId": "3",
"name": "DataSense"
}
},
{
"l": {
"id": "5",
"name": "Julian"
}
},
{
"r": {
"ownerId": "4",
"name": "SmartConnectors"
}
}
]
5.1.12. partition
partition(Array<T>, (item: T) → Boolean): { success: Array<T>, failure: Array<T> }
Separates the array into the elements that satisfy the condition from those that do not.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The array of elements to split. |
|
The condition (or expression) used to match an element in the array. |
Example
This example partitions numbers found within an input array. The
even numbers match the criteria set by the lambda expression
(item) → isEven(item)
. The odd do not. The function generates the
"success"
and "failure"
keys within the output object.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,3,4,5]
---
arr partition (item) -> isEven(item)
1
2
3
4
5
6
7
8
9
10
11
12
{
"success": [
0,
2,
4
],
"failure": [
1,
3,
5
]
}
5.1.13. slice
slice(Array<T>, Number, Number): Array<T>
Selects the interval of elements that satisfy the condition:
from <= indexOf(array) < until
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The array of elements. |
|
The lowest index to include from the array. |
|
The lowest index to exclude from the array. |
Example
This example returns an array that contains the values of indices 1, 2, and 3 from the input array. It excludes the values of indices 0, 4, and 5.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,3,4,5]
---
slice(arr, 1, 4)
1
2
3
4
5
[
1,
2,
3
]
5.1.14. some
some(Array<T>, (T) → Boolean): Boolean
Returns true
if at least one element in the array matches the specified condition.
The function stops iterating after the first element that matches the condition is found.
Parameters
Name | Description |
---|---|
|
The input array. |
|
A condition (or expression) used to match elements in the array. |
Example
This example applies a variety of expressions to elements of several input arrays.
The $
in the condition is the default paramemeter for the current element of the
array that the condition evaluates.
Note that you can replace the default $
parameter with a lambda expression that
contains a named parameter for the current array element.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
%dw 2.0
import * from dw::core::Arrays
output application/json
---
{ "results" : [
"ok" : [
[1,2,3] some (($ mod 2) == 0),
[1,2,3] some ((nextNum) -> (nextNum 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] some ($ == 1),
[1] some ($ == 1)
],
"err" : [
[1,2,3] some ($ == 100),
[1] some ($ == 2)
]
]
}
1
2
3
4
5
6
7
8
9
10
{
"results": [
{
"ok": [ true, true, true, true, true, true, true ]
},
{
"err": [ false, false ]
}
]
}
some(Null, (Nothing) → Boolean): Boolean
Helper function to make some
work with a null
value.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
5.1.15. splitAt
splitAt(Array<T>, Number): Pair<Array<T>, Array<T>>
Splits an array into two at a given position.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The array of elements. |
|
The index at which to split the array. |
Example
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var users = ["Mariano", "Leandro", "Julian"]
---
users splitAt 1
1
2
3
4
5
6
7
8
9
{
"l": [
"Mariano"
],
"r": [
"Leandro",
"Julian"
]
}
5.1.16. splitWhere
splitWhere(Array<T>, (item: T) → Boolean): Pair<Array<T>, Array<T>>
Splits an array into two at the first position where the condition is met.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The array of elements to split. |
|
The condition (or expression) used to match an element in the array. |
Example
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var users = ["Mariano", "Leandro", "Julian", "Tomo"]
---
users splitWhere (item) -> item startsWith "Jul"
1
2
3
4
5
6
7
8
9
10
{
"l": [
"Mariano",
"Leandro"
],
"r": [
"Julian",
"Tomo"
]
}
5.1.17. sumBy
sumBy(Array<T>, (T) → Number): Number
Returns the sum of the values of the elements in an array.
Parameters
Name | Description |
---|---|
|
The input array. |
|
A DataWeave selector that selects the values of the numbers in the input array. |
Example
This example calculates the sum of the values of elements some arrays. Notice
that both of the sumBy
function calls produce the same result.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Arrays
output application/json
---
{
"sumBy" : [
[ { a: 1 }, { a: 2 }, { a: 3 } ] sumBy $.a,
sumBy([ { a: 1 }, { a: 2 }, { a: 3 } ], (item) -> item.a)
]
}
1
{ "sumBy" : [ 6, 6 ] }
5.1.18. take
take(Array<T>, Number): Array<T>
Selects the first n
elements. It returns an empty array when n <= 0
and the original array when n > sizeOf(array)
.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The array of elements. |
|
The number of elements to select. |
Example
This example outputs an array that contains the values of first two elements of the input array.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
var users = ["Mariano", "Leandro", "Julian"]
output application/json
---
take(users, 2)
1
2
3
4
[
"Mariano",
"Leandro"
]
5.1.19. takeWhile
takeWhile(Array<T>, (item: T) → Boolean): Array<T>
Selects elements from the array while the condition is met but stops the selection process when it reaches an element that fails to satisfy the condition.
To select all elements that meet the condition, use the filter
function.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The array of elements. |
|
The condition (or expression) used to match an element in the array. |
Example
This example iterates over the elements in the array and selects only those
where in index is <= 2
and stops selecting elements when it reaches
one that is greater than 2. Notice that it does not select the 3 because 4
precedes 3 in the array. The function outputs the result into an array.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,4,3]
---
arr takeWhile $ <= 2
1
2
3
4
5
[
0,
1,
2
]
6. dw::core::Binaries
This module contains helper functions for working with binaries.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Binaries
to the header of your
DataWeave script.
6.1. Functions
6.1.1. fromBase64
fromBase64(String): Binary
Transforms a Base64 string into a binary value.
Parameters
Name | Description |
---|---|
|
The Base64 string to transform. |
Example
This example takes a Base64 encoded string and transforms it into a binary value. This example assumes that the payload
contains the Base64 string generated from an image in example toBase64.
1
2
3
4
5
6
%dw 2.0
import fromBase64 from dw::core::Binaries
output application/octet-stream
---
fromBase64(payload)
The output of this function is a binary value that represents the image generated in example toBase64.
6.1.2. fromHex
fromHex(String): Binary
Transforms a hexadecimal string into a binary.
Parameters
Name | Description |
---|---|
|
A hexadecimal string to transform. |
Example
This example transforms a hexadecimal string to "Mule".
1
2
3
4
5
%dw 2.0
import * from dw::core::Binaries
output application/json
---
{ "hexToBinary": fromHex("4D756C65") }
1
{ "hexToBinary": "Mule" }
6.1.3. readLinesWith
readLinesWith(Binary, String): Array<String>
Splits the specified binary content into lines and returns the results in an array.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
Binary data to read and split. |
|
String representing the encoding to read. |
Example
This example transforms binary content, which is separated into new
lines (\n
), in a comma-separated array.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Binaries
var content = read("Line 1\nLine 2\nLine 3\nLine 4\nLine 5\n", "application/octet-stream")
output application/json
---
{
lines : (content readLinesWith "UTF-8"),
showType: typeOf(content)
}
1
2
3
4
{
"lines": [ "Line 1", "Line 2", "Line 3", "Line 4", "Line 5" ],
"showType": "Binary"
}
6.1.4. toBase64
toBase64(Binary): String
Transforms a binary value into a Base64 string.
Parameters
Name | Description |
---|---|
|
The binary value to transform. |
Example
This example transforms a binary value into a Base64 encoded string. In this case, the binary value represents an image.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import dw::Crypto
import toBase64 from dw::core::Binaries
var emailChecksum = Crypto::MD5("achaval@gmail.com" as Binary)
var image = readUrl(log("https://www.gravatar.com/avatar/$(emailChecksum)"), "application/octet-stream")
output application/json
---
toBase64(image)
This example outputs a Base64 encoded string. The resulting string was shortened for readability purposes:
1
"/9j/4AAQSkZJRgABAQEAYABgAAD//..."
6.1.5. toHex
toHex(Binary): String
Transforms a binary value into a hexadecimal string.
Parameters
Name | Description |
---|---|
|
The |
Example
This example transforms a binary version of "Mule" (defined in the variable,
myBinary
) to hexadecimal.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Binaries
output application/json
var myBinary = "Mule" as Binary
var testType = typeOf(myBinary)
---
{
"binaryToHex" : toHex(myBinary)
}
1
{ "binaryToHex": "4D756C65" }
6.1.6. writeLinesWith
writeLinesWith(Array<String>, String): Binary
Writes the specified lines and returns the binary content.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
Array of items to write. |
|
String representing the encoding to use when writing. |
Example
This example inserts a new line (\n
) after each iteration. Specifically,
it uses map
to iterate over the result of to(1, 10)
, [1,2,3,4,5]
, then
writes the specified content ("Line $"), which includes the unnamed variable
$
for each number in the array.
Note that without writeLinesWith "UTF-8"
, the expression
{ lines: to(1, 10) map "Line $" }
simply returns
an array of line numbers as the value of an object:
{ "lines": [ "line 1", "line 2", "line 3", "line 4", "line 5" ] }
.
1
2
3
4
5
%dw 2.0
import * from dw::core::Binaries
output application/json
---
{ lines: to(1, 10) map "Line $" writeLinesWith "UTF-8" }
1
2
3
{
"lines": "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\n"
}
7. dw::core::Numbers
This module contains helper functions to work with Numbers.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Numbers
to the header of your
DataWeave script.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
7.1. Functions
7.1.1. fromBinary
fromBinary(String): Number
Transforms from a binary number into a decimal number.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The binary number represented in a |
Example
This example shows how the toBinary
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import fromBinary from dw::core::Numbers
output application/json
---
{
a: fromBinary("-10"),
b: fromBinary("11111000111010111010110100101011100001001110000011010101100010111101001011100000100010011000011101100101101001111101111010110010010100110010100100000000000000000000000000000000000000000000000000000000000000"),
c: fromBinary(0),
d: fromBinary(null),
e: fromBinary("100"),
}
1
2
3
4
5
6
7
{
"a": -2,
"b": 100000000000000000000000000000000000000000000000000000000000000,
"c": 0,
"d": null,
"e": 4
}
fromBinary(Null): Null
Helper function to make fromBinary
work with null value.
7.1.2. fromHex
fromHex(String): Number
Transforms a hexadecimal number into decimal number.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The hexadecimal number represented in a |
Example
This example shows how the toBinary
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import fromHex from dw::core::Numbers
output application/json
---
{
a: fromHex("-1"),
b: fromHex("3e3aeb4ae1383562f4b82261d969f7ac94ca4000000000000000"),
c: fromHex(0),
d: fromHex(null),
e: fromHex("f"),
}
1
2
3
4
5
6
7
{
"a": -1,
"b": 100000000000000000000000000000000000000000000000000000000000000,
"c": 0,
"d": null,
"e": 15
}
fromHex(Null): Null
Helper function to make fromHex
work with null value.
7.1.3. fromRadixNumber
fromRadixNumber(String, Number): Number
Transforms a number in the specified radix into decimal number
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The number text. |
|
The radix number. |
Example
This example shows how the fromRadixNumber
behaves under different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import fromRadixNumber from dw::core::Numbers
output application/json
---
{
a: fromRadixNumber("10", 2),
b: fromRadixNumber("FF", 16)
}
1
2
3
4
{
"a": 2,
"b": 255
}
7.1.4. toBinary
toBinary(Number): String
Transforms a decimal number into a binary number.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input number. |
Example
This example shows how the toBinary
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import toBinary from dw::core::Numbers
output application/json
---
{
a: toBinary(-2),
b: toBinary(100000000000000000000000000000000000000000000000000000000000000),
c: toBinary(0),
d: toBinary(null),
e: toBinary(2),
}
1
2
3
4
5
6
7
{
"a": "-10",
"b": "11111000111010111010110100101011100001001110000011010101100010111101001011100000100010011000011101100101101001111101111010110010010100110010100100000000000000000000000000000000000000000000000000000000000000",
"c": "0",
"d": null,
"e": "10"
}
toBinary(Null): Null
Helper function to make toBinary
work with null value.
7.1.5. toHex
toHex(Number): String
Transforms a decimal number into a hexadecimal number.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input number. |
Example
This example shows how toHex
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import toHex from dw::core::Numbers
output application/json
---
{
a: toHex(-1),
b: toHex(100000000000000000000000000000000000000000000000000000000000000),
c: toHex(0),
d: toHex(null),
e: toHex(15),
}
1
2
3
4
5
6
7
{
"a": "-1",
"b": "3e3aeb4ae1383562f4b82261d969f7ac94ca4000000000000000",
"c": "0",
"d": null,
"e": "f"
}
toHex(Null): Null
Helper function to make toHex
work with null value.
7.1.6. toRadixNumber
toRadixNumber(Number, Number): String
Transforms a decimal number into a number string in other radix.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The decimal number. |
|
The radix of the result number. |
Example
This example shows how the toRadixNumber
behaves under different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import toRadixNumber from dw::core::Numbers
output application/json
---
{
a: toRadixNumber(2, 2),
b: toRadixNumber(255, 16)
}
1
2
3
4
{
"a": "10",
"b": "ff"
}
8. dw::core::Objects
This module contains helper functions to work with Objects.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Objects
to the header of your
DataWeave script.
8.1. Functions
8.1.1. divideBy
divideBy(Object, Number): Array<Object>
Breaks up an object into sub-objects that contain the specified number of key-value pairs.
If there are fewer key-value pairs in an object than the specified number, the function will fill the object with those pairs. If there are more pairs, the function will fill another object with the extra pairs.
Parameters
Name | Description |
---|---|
|
Key-value pairs in the source object. |
|
The number of key-value pairs allowed in an object. |
Example
This example breaks up objects into sub-objects based on the specified amount
.
1
2
3
4
5
%dw 2.0
import divideBy from dw::core::Objects
output application/json
---
{ "divideBy" : {"a": 1, "b" : true, "a" : 2, "b" : false, "c" : 3} divideBy 2 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"divideBy": [
{
"a": 1,
"b": true
},
{
"a": 2,
"b": false
},
{
"c": 3
}
]
}
8.1.2. entrySet
entrySet(T): Array<{| key: Key, value: Any, attributes: Object |}>
Returns an array of key-value pairs that describe the key, value, and any attributes in the input object.
This method has been Deprecated and please use entriesOf from Core module
Parameters
Name | Description |
---|---|
|
The |
Example
This example returns the key, value, and attributes in the object specified
in the variable myVar
.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Objects
var myVar = read('<xml attr="x"><a>true</a><b>1</b></xml>', 'application/xml')
output application/json
---
{ "entrySet" : entrySet(myVar) }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"entrySet": [
{
"key": "xml",
"value": {
"a": "true",
"b": "1"
},
"attributes": {
"attr": "x"
}
}
]
}
8.1.3. everyEntry
everyEntry(Object, (value: Any, key: Key) → Boolean): Boolean
Returns true
if every entry in the object matches the condition.
The function stops iterating after the first negative evaluation of an element in the array.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
object |
The object to be evaluated |
condition |
The condition that will be verified for every element |
Example
This example shows how the everyEntry
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import everyEntry from dw::core::Objects
output application/json
---
{
a: {} everyEntry (value, key) -> value is String,
b: {a: "", b: "123"} everyEntry (value, key) -> value is String,
c: {a: "", b: 123} everyEntry (value, key) -> value is String,
d: {a: "", b: 123} everyEntry (value, key) -> key as String == "a",
e: {a: ""} everyEntry (value, key) -> key as String == "a",
f: null everyEntry ((value, key) -> key as String == "a")
}
1
2
3
4
5
6
7
8
{
"a": true,
"b": true,
"c": false,
"d": false,
"e": true,
"f": true
}
everyEntry(Null, (Nothing, Nothing) → Boolean): Boolean
Helper function that makes everyEntry work with null values
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
8.1.4. keySet
keySet(T): ?
Returns an array of key names from an object.
This method has been Deprecated and please use keysOf from Core module
Parameters
Name | Description |
---|---|
|
The object to evaluate. |
Example
This example returns the keys from the input object.
1
2
3
4
5
%dw 2.0
import * from dw::core::Objects
output application/json
---
{ "keySet" : keySet({ "a" : true, "b" : 1}) }
1
{ "keySet" : ["a","b"] }
Example
This example illustrates a difference between keySet
and nameSet
.
Notice that keySet
retains the attributes (name
and lastName
)
and namespaces (xmlns
) from the XML input, while nameSet
returns
null
for them because it does not retain them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
%dw 2.0
import * from dw::core::Objects
var myVar = read('<users xmlns="http://test.com">
<user name="Mariano" lastName="Achaval"/>
<user name="Stacey" lastName="Duke"/>
</users>', 'application/xml')
output application/json
---
{ keySetExample: flatten([keySet(myVar.users) map $.#,
keySet(myVar.users) map $.@])
}
++
{ nameSet: flatten([nameSet(myVar.users) map $.#,
nameSet(myVar.users) map $.@])
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"keySet": [
"http://test.com",
"http://test.com",
{
"name": "Mariano",
"lastName": "Achaval"
},
{
"name": "Stacey",
"lastName": "Duke"
}
],
"nameSet": [
null,
null,
null,
null
]
}
8.1.5. mergeWith
mergeWith(T, V): ?
Appends any key-value pairs from a source object to a target object.
If source and target objects have the same key, the function appends that source object to the target and removes that target object from the output.
Parameters
Name | Description |
---|---|
|
The object to append to the |
|
The object to which the |
Example
This example appends the source objects to the target. Notice that
"a" : true,
is removed from the output, and "a" : false
is appended
to the target.
1
2
3
4
5
%dw 2.0
import mergeWith from dw::core::Objects
output application/json
---
{ "mergeWith" : { "a" : true, "b" : 1} mergeWith { "a" : false, "c" : "Test"} }
1
2
3
4
5
"mergeWith": {
"b": 1,
"a": false,
"c": "Test"
}
mergeWith(Null, T): T
Helper method to make mergeWith
null friendly.
mergeWith(T, Null): T
Helper method to make mergeWith
null friendly.
8.1.6. nameSet
nameSet(Object): Array<String>
Returns an array of keys from an object.
This method has been Deprecated and please use namesOf from Core module
Parameters
Name | Description |
---|---|
|
The object to evaluate. |
Example
This example returns the keys from the input object.
1
2
3
4
5
%dw 2.0
import * from dw::core::Objects
output application/json
---
{ "nameSet" : nameSet({ "a" : true, "b" : 1}) }
1
{ "nameSet" : ["a","b"] }
8.1.7. someEntry
someEntry(Object, (value: Any, key: Key) → Boolean): Boolean
Returns true
if at least one entry in the object matches the specified condition.
The function stops iterating after the first element that matches the condition is found.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
obj |
The object to be evaluated |
condition |
The condition that will be verified for every element |
Example
This example shows how the someEntry
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import someEntry from dw::core::Objects
output application/json
---
{
a: {} someEntry (value, key) -> value is String,
b: {a: "", b: "123"} someEntry (value, key) -> value is String,
c: {a: "", b: 123} someEntry (value, key) -> value is String,
d: {a: "", b: 123} someEntry (value, key) -> key as String == "a",
e: {a: ""} someEntry (value, key) -> key as String == "b",
f: null someEntry (value, key) -> key as String == "a"
}
1
2
3
4
5
6
7
8
{
"a": false,
"b": true,
"c": true,
"d": true,
"e": false,
"f": false
}
someEntry(Null, (value: Nothing, key: Nothing) → Boolean): Boolean
Helper function that makes someEntry work with null values
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
8.1.8. takeWhile
takeWhile(Object, (value: Any, key: Key) → Boolean): Object
Selects key-value pairs from the object while the condition is met.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
|
The object to be filtered. |
|
The condition (or expression) used to match a key-value pairs in the object. |
Example
This example iterates over the key-value pairs in the object and selects the elements while the condition is met. It outputs the result into an object.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Objects
output application/json
var obj = {
"a": 1,
"b": 2,
"c": 5,
"d": 1
}
---
obj takeWhile ((value, key) -> value < 3)
1
2
3
4
{
"a": 1,
"b": 2
}
8.1.9. valueSet
valueSet({ (K)?: V }): Array<V>
Returns an array of the values from key-value pairs in an object.
This method has been Deprecated and please use valuesOf from Core module
Parameters
Name | Description |
---|---|
|
The object to evaluate. |
Example
This example returns the values from the input object.
1
2
3
4
5
%dw 2.0
import * from dw::core::Objects
output application/json
---
{ "valueSet" : valueSet({a: true, b: 1}) }
1
{ "valueSet" : [true,1] }
9. dw::core::Periods
9.1. Functions
9.1.1. between
between(Date, Date): Period
Returns a Period (P) value consisting of the number of years, months, and days between two Date values.
The start date is included, but the end date is not.
The result of this method can be a negative period
if the end date (endDateExclusive
) is before the
start date (startDateInclusive
).
Note that the first parameter of the function is the endDateExclusive
and the second one is the startDateInclusive
.
Parameters
Name | Description |
---|---|
endDateExclusive |
The end date, exclusive. |
startDateInclusive |
The start date, inclusive. |
Example
This example shows how between
behaves with different inputs.
1
2
3
4
5
6
7
8
import * from dw::core::Periods
output application/json
---
{
a: between(|2010-12-12|,|2010-12-10|),
b: between(|2011-12-11|,|2010-11-10|),
c: between(|2020-02-29|,|2020-03-30|)
}
1
2
3
4
5
{
"a": "P2D",
"b": "P1Y1M1D",
"c": "P-1M-1D"
}
10. dw::core::Strings
This module contains helper functions to work with Strings.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Strings
to the header of your
DataWeave script.
10.1. Functions
10.1.1. appendIfMissing
appendIfMissing(String, String): String
Appends the suffix
to the end of the text
if the text
does not already
ends with the suffix
.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
The text used as the suffix. |
Example
This example shows how appendIfMissing
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import appendIfMissing from dw::core::Strings
output application/json
---
{
"a": appendIfMissing(null, ""),
"b": appendIfMissing("abc", ""),
"c": appendIfMissing("", "xyz") ,
"d": appendIfMissing("abc", "xyz") ,
"e": appendIfMissing("abcxyz", "xyz")
}
1
2
3
4
5
6
7
{
"a": null,
"b": "abc",
"c": "xyz",
"d": "abcxyz",
"e": "abcxyz"
}
appendIfMissing(Null, String): Null
Helper function to make appendIfMissing
work with null
value.
10.1.2. camelize
camelize(String): String
Returns a string in camel case based on underscores in the string.
All underscores are deleted, including any underscores at the beginning of the string.
Parameters
Name | Description |
---|---|
|
The string to convert to camel case. |
Example
This example converts a string that contains underscores to camel case.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a" : camelize("customer_first_name"),
"b" : camelize("_name_starts_with_underscore")
}
1
2
3
4
{
"a": "customerFirstName",
"b": "nameStartsWithUnderscore"
}
camelize(Null): Null
Helper function that allows camelize
to work with null values.
10.1.3. capitalize
capitalize(String): String
Capitalizes the first letter of each word in a string.
It also removes underscores between words and puts a space before each capitalized word.
Parameters
Name | Description |
---|---|
|
The string to capitalize. |
Example
This example capitalizes a set of strings.
1
2
3
4
5
6
7
8
9
10
%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")
}
1
2
3
4
5
6
{
"a": "Customer",
"b": "Customer First Name",
"c": "Customer Name",
"d": "Customer Name"
}
capitalize(Null): Null
Helper function that allows capitalize to work with null values.
10.1.4. charCode
charCode(String): Number
Returns the Unicode for the first character in an input string.
For an empty string, the function fails and returns Unexpected empty string
.
Parameters
Name | Description |
---|---|
|
The input string. |
Example
This example returns Unicode for the "M" in "Mule".
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"charCode" : charCode("Mule")
}
1
{ "charCode" : 77 }
10.1.5. charCodeAt
charCodeAt(String, Number): Number
Returns the Unicode for a character at the specified index.
This function fails if the index is invalid.
Parameters
Name | Description |
---|---|
|
The input string. |
|
The index (a |
Example
This example returns Unicode for the "u" at index 1
in "MuleSoft".
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"charCodeAt" : charCodeAt("MuleSoft", 1)
}
1
{ "charCodeAt": 117 }
10.1.6. dasherize
dasherize(String): String
Replaces spaces, underscores, and camel-casing in a string with dashes (hyphens).
If no spaces, underscores, and camel-casing are present, the output will match the input.
Parameters
Name | Description |
---|---|
|
The input string. |
Example
This example replaces the spaces, underscores, and camel-casing in the input. Notice that the input "customer" is not modified in the output.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a" : dasherize("customer"),
"b" : dasherize("customer_first_name"),
"c" : dasherize("customer NAME"),
"d" : dasherize("customerName")
}
1
2
3
4
5
6
{
"a": "customer",
"b": "customer-first-name",
"c": "customer-name",
"d": "customer-name"
}
dasherize(Null): Null
Helper function that allows dasherize to work with null values.
10.1.7. fromCharCode
fromCharCode(Number): String
Returns a character that matches the specified Unicode.
Parameters
Name | Description |
---|---|
|
The input Unicode (a |
Example
This example inputs the Unicode number 117
to return the character "u".
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"fromCharCode" : fromCharCode(117)
}
1
{ "fromCharCode": "u" }
10.1.8. isAlpha
isAlpha(String): Boolean
Checks if the text
contains only Unicode digits. A decimal point is not a Unicode digit and returns false
.
Note that the method does not allow for a leading sign, either positive or negative.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
Example
This example shows how isNumeric
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import isAlpha from dw::core::Strings
output application/json
---
{
"a": isAlpha(null),
"b": isAlpha(""),
"c": isAlpha(" "),
"d": isAlpha("abc"),
"e": isAlpha("ab2c"),
"f": isAlpha("ab-c")
}
1
2
3
4
5
6
7
8
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": false
}
isAlpha(Null): Boolean
Helper function for isAlpha
so it works with null
value.
10.1.9. isAlphanumeric
isAlphanumeric(String): Boolean
Checks if the text
contains only Unicode letters or digits.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
Example
This example shows how isAlphanumeric
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
import isAlphanumeric from dw::core::Strings
output application/json
---
{
"a": isAlphanumeric(null),
"b": isAlphanumeric(""),
"c": isAlphanumeric(" "),
"d": isAlphanumeric("abc"),
"e": isAlphanumeric("ab c"),
"f": isAlphanumeric("ab2c"),
"g": isAlphanumeric("ab-c")
}
1
2
3
4
5
6
7
8
9
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": true,
"g": false
}
isAlphanumeric(Null): Boolean
Helper function for isAlphanumeric
so it works with null
value.
10.1.10. isLowerCase
isLowerCase(String): Boolean
Checks if the text
contains only lowercase characters.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
Example
This example shows how isNumeric
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import isLowerCase from dw::core::Strings
output application/json
---
{
"a": isLowerCase(null),
"b": isLowerCase(""),
"c": isLowerCase(" "),
"d": isLowerCase("abc"),
"e": isLowerCase("aBC"),
"f": isLowerCase("a c"),
"g": isLowerCase("a1c"),
"h": isLowerCase("a/c")
}
1
2
3
4
5
6
7
8
9
10
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": false,
"g": false,
"h": false
}
isLowerCase(Null): Boolean
Helper function for isLowerCase
so it works with null
value.
10.1.11. isNumeric
isNumeric(String): Boolean
Checks if the text
contains only Unicode digits.
A decimal point is not a Unicode digit and returns false. Note that the method does not allow for a leading sign, either positive or negative.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
Example
This example shows how isNumeric
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
%dw 2.0
import isNumeric from dw::core::Strings
output application/json
---
{
"a": isNumeric(null),
"b": isNumeric(""),
"c": isNumeric(" "),
"d": isNumeric("123"),
"e": isNumeric("१२३"),
"f": isNumeric("12 3"),
"g": isNumeric("ab2c"),
"h": isNumeric("12-3"),
"i": isNumeric("12.3"),
"j": isNumeric("-123"),
"k": isNumeric("+123")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": true,
"f": false,
"g": false,
"h": false,
"i": false,
"j": false,
"k": false
}
isNumeric(Null): Boolean
Helper function for isNumeric
so it works with null
value.
10.1.12. isUpperCase
isUpperCase(String): Boolean
Checks if the text
contains only uppercase characters.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
Example
This example shows how isNumeric
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import isUpperCase from dw::core::Strings
output application/json
---
{
"a": isUpperCase(null),
"b": isUpperCase(""),
"c": isUpperCase(" "),
"d": isUpperCase("ABC"),
"e": isUpperCase("aBC"),
"f": isUpperCase("A C"),
"g": isUpperCase("A1C"),
"h": isUpperCase("A/C")
}
1
2
3
4
5
6
7
8
9
10
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": false,
"g": false,
"h": false
}
isUpperCase(Null): Boolean
Helper function for isUpperCase
so that it works with null
value.
10.1.13. isWhitespace
isWhitespace(String): Boolean
Checks if the text
contains only whitespace.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
Example
This example shows how isWhitespace
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import isWhitespace from dw::core::Strings
output application/json
---
{
"a": isWhitespace(null),
"b": isWhitespace(""),
"c": isWhitespace(" "),
"d": isWhitespace("abc"),
"e": isWhitespace("ab2c"),
"f": isWhitespace("ab-c")
}
1
2
3
4
5
6
7
8
{
"a": false,
"b": true,
"c": true,
"d": false,
"e": false,
"f": false
}
isWhitespace(Null): Boolean
Helper function for isWhitespace
so it works with null
value.
10.1.14. leftPad
leftPad(String, Number, String): String
The specified text
is left-padded to the size
using the padText
.
By default padText
is " "
.
Returns left-padded String
or original String
if no padding is necessary.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
The size to pad to. |
|
The text to pad with. It defaults to one space if not specified. |
Example
This example shows how leftPad
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": leftPad(null, 3),
"b": leftPad("", 3),
"c": leftPad("bat", 5),
"d": leftPad("bat", 3),
"e": leftPad("bat", -1)
}
1
2
3
4
5
6
7
{
"a": null,
"b": " ",
"c": " bat",
"d": "bat",
"e": "bat"
}
leftPad(Null, Number, String): Null
Helper function to make leftPad
work with null
value.
10.1.15. ordinalize
ordinalize(Number): String
Returns a number as an ordinal, such as 1st
or 2nd
.
Parameters
Name | Description |
---|---|
|
An input number to return as an ordinal. |
Example
This example returns a variety of input numbers as ordinals.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a" : ordinalize(1),
"b": ordinalize(2),
"c": ordinalize(5),
"d": ordinalize(103)
}
1
2
3
4
5
6
{
"a": "1st",
"b": "2nd",
"c": "5th",
"d": "103rd"
}
ordinalize(Null): Null
Helper function that allows ordinalize
to work with null values.
10.1.16. pluralize
pluralize(String): String
Pluralizes a singular string.
If the input is already plural (for example, "boxes"), the output will match the input.
Parameters
Name | Description |
---|---|
|
The string to pluralize. |
Example
This example pluralizes the input string "box" to return "boxes".
1
2
3
4
5
%dw 2.0
import * from dw::core::Strings
output application/json
---
{ "pluralize" : pluralize("box") }
1
{ "pluralize" : "boxes" }
pluralize(Null): Null
Helper function that allows pluralize to work with null values.
10.1.17. prependIfMissing
prependIfMissing(String, String): String
Prepends the prefix
to the beginning of the string if the text
does not
already start with that prefix.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
The text to use as prefix. |
Example
This example shows how prependIfMissing
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import prependIfMissing from dw::core::Strings
output application/json
---
{
"a": prependIfMissing(null, ""),
"b": prependIfMissing("abc", ""),
"c": prependIfMissing("", "xyz"),
"d": prependIfMissing("abc", "xyz"),
"e": prependIfMissing("xyzabc", "xyz")
}
1
2
3
4
5
6
7
{
"a": null,
"b": "abc",
"c": "xyz",
"d": "xyzabc",
"e": "xyzabc"
}
prependIfMissing(Null, String): Null
Helper function to make prependIfMissing
work with null
value.
10.1.18. repeat
repeat(String, Number): String
Repeats a text
the number of specified times
.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
Number of times to repeat char. Negative is treated as zero. |
Example
This example shows how repeat
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": repeat("e", 0),
"b": repeat("e", 3),
"c": repeat("e", -2)
}
1
2
3
4
5
{
"a": "",
"b": "eee",
"c": ""
}
10.1.19. rightPad
rightPad(String, Number, String): String
The specified text
is right-padded to the size
using the padText
.
By default padText
is " "
.
Returns right padded String
or original String
if no padding is necessary.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
The size to pad to. |
|
The text to pad with. It defaults to one space if not specified. |
Example
This example shows how rightPad
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": rightPad(null, 3),
"b": rightPad("", 3),
"c": rightPad("bat", 5),
"d": rightPad("bat", 3),
"e": rightPad("bat", -1)
}
1
2
3
4
5
6
7
{
"a": null,
"b": " ",
"c": "bat ",
"d": "bat",
"e": "bat"
}
rightPad(Null, Number, String): Null
Helper function to make rightPad
work with null
value.
10.1.20. singularize
singularize(String): String
Converts a plural string to its singular form.
If the input is already singular (for example, "box"), the output will match the input.
Parameters
Name | Description |
---|---|
|
The string to convert to singular form. |
Example
This example converts the input string "boxes" to return "box".
1
2
3
4
5
%dw 2.0
import * from dw::core::Strings
output application/json
---
{ "singularize" : singularize("boxes") }
1
{ "singularize" : "box" }
singularize(Null): Null
Helper function that allows singularize to work with null values.
10.1.21. substringAfter
substringAfter(String, String): String
Gets the substring after the first occurrence of a separator. The separator is not returned.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
String to search for. |
Example
This example shows how substringAfter
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": substringAfter(null, "'"),
"b": substringAfter("", "-"),
"c": substringAfter("abc", "b"),
"d": substringAfter("abcba", "b"),
"e": substringAfter("abc", "d"),
"f": substringAfter("abc", "")
}
1
2
3
4
5
6
7
8
9
{
"a": null,
"b": "",
"c": "c",
"d": "cba",
"e": "",
"f": "bc"
}
substringAfter(Null, String): Null
Helper function for substringAfter
work with null value.
10.1.22. substringAfterLast
substringAfterLast(String, String): String
Gets the substring after the last occurrence of a separator. The separator is not returned.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
String to search for. |
Example
This example shows how substringAfterLast
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": substringAfterLast(null, "'"),
"b": substringAfterLast("", "-"),
"c": substringAfterLast("abc", "b"),
"d": substringAfterLast("abcba", "b"),
"e": substringAfterLast("abc", "d"),
"f": substringAfterLast("abc", "")
}
1
2
3
4
5
6
7
8
{
"a": null,
"b": "",
"c": "c",
"d": "a",
"e": "",
"f": null
}
substringAfterLast(Null, String): Null
Helper function for substringAfterLast
to work with null
value.
10.1.23. substringBefore
substringBefore(String, String): String
Gets the substring before the first occurrence of a separator. The separator is not returned.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
String to search for. |
Example
This example shows how substringBefore
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": substringBefore(null, "'"),
"b": substringBefore("", "-"),
"c": substringBefore("abc", "b"),
"d": substringBefore("abc", "c"),
"e": substringBefore("abc", "d"),
"f": substringBefore("abc", "")
}
1
2
3
4
5
6
7
8
{
"a": null,
"b": "",
"c": "a",
"d": "ab",
"e": "",
"f": ""
}
substringBefore(Null, String): Null
Helper function for substringBefore
to work with null value.
10.1.24. substringBeforeLast
substringBeforeLast(String, String): String
Gets the substring before the last occurrence of a separator. The separator is not returned.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
String to search for. |
Example
This example shows how substringBeforeLast
behaves with different inputs
and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": substringBeforeLast(null, "'"),
"b": substringBeforeLast("", "-"),
"c": substringBeforeLast("abc", "b"),
"d": substringBeforeLast("abcba", "b"),
"e": substringBeforeLast("abc", "d"),
"f": substringBeforeLast("abc", "")
}
1
2
3
4
5
6
7
8
{
"a": null,
"b": "",
"c": "a",
"d": "abc",
"e": "",
"f": "a"
}
substringBeforeLast(Null, String): Null
Helper function for substringBeforeLast
to work with null value.
10.1.25. underscore
underscore(String): String
Replaces hyphens, spaces, and camel-casing in a string with underscores.
If no hyphens, spaces, and camel-casing are present, the output will match the input.
Parameters
Name | Description |
---|---|
|
The input string. |
Example
This example replaces the hyphens and spaces in the input. Notice that the input "customer" is not modified in the output.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a" : underscore("customer"),
"b" : underscore("customer-first-name"),
"c" : underscore("customer NAME"),
"d" : underscore("customerName")
}
1
2
3
4
5
6
{
"a": "customer",
"b": "customer_first_name",
"c": "customer_name",
"d": "customer_name"
}
underscore(Null): Null
Helper function that allows underscore to work with null values.
10.1.26. unwrap
unwrap(String, String): String
Unwraps a given text
from a wrapper
text.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
The text used to unwrap. |
Example
This example shows how unwrap
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
import unwrap from dw::core::Strings
output application/json
---
{
"a": unwrap(null, ""),
"b": unwrap(null, '\0'),
"c": unwrap("'abc'", "'"),
"d": unwrap("AABabcBAA", 'A'),
"e": unwrap("A", '#'),
"f": unwrap("#A", '#'),
"g": unwrap("A#", '#')
}
1
2
3
4
5
6
7
8
9
{
"a": null,
"b": null,
"c": "abc",
"d": "ABabcBA",
"e": "A",
"f": "A#",
"g": "#A"
}
unwrap(Null, String): Null
Helper function to make unwrap
work with null
value.
10.1.27. withMaxSize
withMaxSize(String, Number): String
Makes sure that the string length is a big as the specified maxLength. If it is bigger it wil cut the text starting from left.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
The maximum length of the string. |
Example
This example shows how withMaxSize
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import withMaxSize from dw::core::Strings
output application/json
---
{
a: "123" withMaxSize 10,
b: "123" withMaxSize 3,
c: "123" withMaxSize 2,
d: "" withMaxSize 0,
e: null withMaxSize 23,
}
1
2
3
4
5
6
7
{
"a": "123",
"b": "123",
"c": "12",
"d": "",
"e": null
}
withMaxSize(Null, Number): Null
Helper function for withMaxSize
so it works with null
value.
10.1.28. wrapIfMissing
wrapIfMissing(String, String): String
Wraps text
with wrapper
if that wrapper
is missing from the start or
end of the given string.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
The content used to wrap. |
Example
This example shows how wrapIfMissing
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": wrapIfMissing(null, "'"),
"b": wrapIfMissing("", "'"),
"c": wrapIfMissing("ab", "x"),
"d": wrapIfMissing("'ab'", "'"),
"e": wrapIfMissing("/", '/'),
"f": wrapIfMissing("a/b/c", '/'),
"g": wrapIfMissing("/a/b/c", '/'),
"h": wrapIfMissing("a/b/c/", '/')
}
1
2
3
4
5
6
7
8
9
10
{
"a": null,
"b": "'",
"c": "xabx",
"d": "'ab'",
"e": "/",
"f": "/a/b/c/",
"g": "/a/b/c/",
"h": "/a/b/c/"
}
wrapIfMissing(Null, String): Null
Helper function for wrapIfMissing
to work with null
value.
10.1.29. wrapWith
wrapWith(String, String): String
Wraps the specified text
with the given wrapper
.
Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
Parameters
Name | Description |
---|---|
|
The input string. |
|
The content used to wrap. |
Example
This example shows how wrapWith
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": wrapWith(null, "'"),
"b": wrapWith("", "'"),
"c": wrapWith("ab", "x"),
"d": wrapWith("'ab'", "'"),
"e": wrapWith("ab", "'")
}
1
2
3
4
5
6
7
{
"a": null,
"b": "''",
"c": "xabx",
"d": "''ab''",
"e": "'ab'"
}
wrapWith(Null, String): Null
Helper function for wrapWith
to work with null value.
11. dw::core::Types
This module allows to introspect a Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
11.1. Functions
11.1.1. arrayItem
arrayItem(Type): Type
Returns an the kind of Array the given type is. It will fail if it is not an Array Type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the intersectionItems
behaves under different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AType = {name: String} & {age: Number}
output application/json
---
{
a: intersectionItems(AType)
}
1
2
3
{
"a": ["Object","Object"]
}
11.1.2. baseTypeOf
baseTypeOf(Type): Type
Returns an the base Type the given Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the baseTypeOf
behaves under different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AType = String {format: "YYYY-MM-dd"}
output application/json
---
{
a: baseTypeOf(AType)
}
1
2
3
{
"a": "String"
}
11.1.3. functionParamTypes
functionParamTypes(Type): Array<FunctionParam>
Returns the list of parameters of the given function type. Fails if the provided type is not a Function
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The function type |
Example
This example shows how the functionParamTypes
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
output application/json
---
import * from dw::core::Types
type AFunction = (String, Number) -> Number
type AFunction2 = () -> Number
---
{
a: functionParamTypes(AFunction),
b: functionParamTypes(AFunction2)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"a": [
{
"paramType": "String",
"optional": false
},
{
"paramType": "Number",
"optional": false
}
],
"b": [
]
}
11.1.4. functionReturnType
functionReturnType(Type): Type | Null
Returns the type of the return type of a Function. Fails if the provided type is not a Function
_Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later._
Parameters
Name | Description |
---|---|
t |
The function type |
Example
This example shows how the functionReturnType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
output application/json
---
import * from dw::core::Types
type AFunction = (String, Number) -> Number
type AFunction2 = () -> Number
---
{
a: functionReturnType(AFunction),
b: functionReturnType(AFunction2)
}
1
2
3
4
{
"a": "Number",
"b": "Number"
}
11.1.5. intersectionItems
intersectionItems(Type): Array<Type>
Returns an Array of all the Types the Intersection Type is defined with. It will fail if it is not an Intersection Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the intersectionItems
behaves under different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AType = {name: String} & {age: Number}
output application/json
---
{
a: intersectionItems(AType)
}
1
2
3
{
"a": ["Object","Object"]
}
11.1.6. isAnyType
isAnyType(Type): Boolean
Returns true if a Type represent a Any Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isAnyType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type AAny = Any
output application/json
---
{
a: isAnyType(AAny),
b: isAnyType(Any),
c: isAnyType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.7. isArrayType
isArrayType(Type): Boolean
Returns true if the given type is an Array Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isArrayType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type AType = Array<String>
output application/json
---
{
a: isObjectType(AType),
b: isObjectType(Boolean),
}
1
2
3
4
{
"a": true,
"b": false
}
11.1.8. isBinaryType
isBinaryType(Type): Boolean
Returns true if a Type represent a Binary Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isBinaryType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ABinary = Binary
output application/json
---
{
a: isBinaryType(ABinary),
b: isBinaryType(Binary),
c: isBinaryType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.9. isBooleanType
isBooleanType(Type): Boolean
Returns true if a Type represent a Boolean Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isBooleanType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ABoolean = Boolean
output application/json
---
{
a: isBooleanType(ABoolean),
b: isBooleanType(Boolean),
c: isBooleanType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.10. isDateTimeType
isDateTimeType(Type): Boolean
Returns true if a Type represent a LocalDateTime Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isDateTimeType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ADateTime = DateTime
output application/json
---
{
a: isDateTimeType(ADateTime),
b: isDateTimeType(DateTime),
c: isDateTimeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.11. isDateType
isDateType(Type): Boolean
Returns true if a Type represent a Date Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isDateType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ADate = Date
output application/json
---
{
a: isDateType(ADate),
b: isDateType(Date),
c: isDateType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.12. isFunctionType
isFunctionType(Type): Boolean
Returns true if a Type represent a Function Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isFunctionType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type AFunction = (String) -> String
output application/json
---
{
a: isFunctionType(AFunction),
b: isFunctionType(Boolean)
}
1
2
3
4
{
"a": true,
"b": false
}
11.1.13. isIntersectionType
isIntersectionType(Type): Boolean
Returns true if the given type is an Intersection Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isIntersectionType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type AType = {name: String} & {age: Number}
output application/json
---
{
a: isIntersectionType(AType),
b: isIntersectionType(Boolean),
}
1
2
3
4
{
"a": true,
"b": false
}
11.1.14. isKeyType
isKeyType(Type): Boolean
Returns true if a Type represent a Key Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isKeyType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type AKey = Key
output application/json
---
{
a: isKeyType(AKey),
b: isKeyType(Key),
c: isKeyType(Boolean),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.15. isLiteralType
isLiteralType(Type): Boolean
Returns true if a Type represent a literal Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isLiteralType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ALiteralType = "Mariano"
output application/json
---
{
a: isLiteralType(ALiteralType),
b: isLiteralType(Boolean)
}
1
2
3
4
{
"a": true,
"b": false
}
11.1.16. isLocalDateTimeType
isLocalDateTimeType(Type): Boolean
Returns true if a Type represent a DateTime Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isLocalDateTimeType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ALocalDateTime = LocalDateTime
output application/json
---
{
a: isLocalDateTimeType(ALocalDateTime),
b: isLocalDateTimeType(LocalDateTime),
c: isLocalDateTimeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.17. isLocalTimeType
isLocalTimeType(Type): Boolean
Returns true if a Type represent a LocalTime Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isLocalTimeType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ALocalTime = LocalTime
output application/json
---
{
a: isLocalTimeType(ALocalTime),
b: isLocalTimeType(LocalTime),
c: isLocalTimeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.18. isNamespaceType
isNamespaceType(Type): Boolean
Returns true if a Type represent a Namespace Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isNamespaceType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ANamespace = Namespace
output application/json
---
{
a: isNamespaceType(ANamespace),
b: isNamespaceType(Namespace),
c: isNamespaceType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.19. isNothingType
isNothingType(Type): Boolean
Returns true if a Type represent a Nothing Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isNothingType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ANothing = Nothing
output application/json
---
{
a: isNothingType(ANothing),
b: isNothingType(Nothing),
c: isNothingType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.20. isNullType
isNullType(Type): Boolean
Returns true if a Type represent a Null Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isNullType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ANull = Null
output application/json
---
{
a: isNullType(ANull),
b: isNullType(Null),
c: isNullType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.21. isNumberType
isNumberType(Type): Boolean
Returns true if a Type represent a Number Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isNumberType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ANumber = Number
output application/json
---
{
a: isNumberType(ANumber),
b: isNumberType(Number),
c: isNumberType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.22. isObjectType
isObjectType(Type): Boolean
Returns true if the given type is an Object Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isObjectType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type AType = {name: String}
output application/json
---
{
a: isObjectType(AType),
b: isObjectType(Boolean),
}
1
2
3
4
{
"a": true,
"b": false
}
11.1.23. isPeriodType
isPeriodType(Type): Boolean
Returns true if a Type represent a Period Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isPeriodType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type APeriod = Period
output application/json
---
{
a: isPeriodType(APeriod),
b: isPeriodType(Period),
c: isPeriodType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.24. isRangeType
isRangeType(Type): Boolean
Returns true if a Type represent a Range Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isRangeType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ARange = Range
output application/json
---
{
a: isNamespaceType(ARange),
b: isNamespaceType(Range),
c: isNamespaceType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.25. isReferenceType
isReferenceType(Type): Boolean
Returns true if the specified type is a Reference.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
Example
This example shows how the isReferenceType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
output application/json
---
import * from dw::core::Types
type AArray = Array<String> {n: 1}
type AArray2 = Array<AArray>
---
{
a: isReferenceType( AArray),
b: isReferenceType(arrayItem(AArray2)),
c: isReferenceType(String)
}
1
2
3
4
5
{
"a": false,
"b": true,
"c": false
}
11.1.26. isRegexType
isRegexType(Type): Boolean
Returns true if a Type represent a Regex Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isRegexType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ARegex = Regex
output application/json
---
{
a: isRegexType(ARegex),
b: isRegexType(Regex),
c: isRegexType(Boolean),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.27. isStringType
isStringType(Type): Boolean
Returns true if a Type represent a String Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isStringType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type AString = String
output application/json
---
{
a: isStringType(AString),
b: isStringType(String),
c: isStringType(Boolean),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.28. isTimeType
isTimeType(Type): Boolean
Returns true if a Type represent a Time Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isTimeType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ATime = Time
output application/json
---
{
a: isTimeType(ATime),
b: isTimeType(Time),
c: isTimeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.29. isTimeZoneType
isTimeZoneType(Type): Boolean
Returns true if a Type represent a TimeZone Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isTimeZoneType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type ATimeZone = TimeZone
output application/json
---
{
a: isTimeZoneType(ATimeZone),
b: isTimeZoneType(TimeZone),
c: isTimeZoneType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.30. isTypeType
isTypeType(Type): Boolean
Returns true if a Type represent a Type Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isTypeType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type AType = Type
output application/json
---
{
a: isTypeType(AType),
b: isTypeType(Type),
c: isTypeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.31. isUnionType
isUnionType(Type): Boolean
Returns true if the given type is a Union Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isUnionType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type AType = String | Number
output application/json
---
{
a: isUnionType(AType),
b: isUnionType(Boolean),
}
1
2
3
4
{
"a": true,
"b": false
}
11.1.32. isUriType
isUriType(Type): Boolean
Returns true if a Type represent a Uri Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the isUriType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Types
type AUri = Uri
output application/json
---
{
a: isUriType(AUri),
b: isUriType(Uri),
c: isUriType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.33. literalValueOf
literalValueOf(Type): String | Number | Boolean
Returns the value of the literal Type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the literalValueOf
behaves under different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AType = "Mariano"
output application/json
---
{
a: literalValueOf(AType)
}
1
2
3
{
"a": "Mariano"
}
11.1.34. metadataOf
metadataOf(Type): Object
Returns an the metadata attached to the given type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The type to be checked |
Example
This example shows how the metadataOf
behaves under different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AType = String {format: "YYYY-MM-dd"}
output application/json
---
{
a: metadataOf(AType)
}
1
2
3
{
"a": {"format": "YYYY-MM-dd"}
}
11.1.35. nameOf
nameOf(Type): String
Returns the name of a given type
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
Name | Description |
---|---|
t |
The Type to query |
Example
This example shows how the nameOf
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
output application/json
---
import * from dw::core::Types
type AArray = Array<String> {n: 1}
type AArray2 = Array<String>
---
{
a: nameOf(AArray),
b: nameOf(AArray2),
c: nameOf(String)
}
1
2
3
4
5
{
"a": "AArray",
"b": "AArray2",
"c": "String"
}
11.1.36. objectFields
objectFields(Type): Array<Field>
Returns the array of fields of the given object type. Fails if the type is not an Object
_Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later._
Parameters
Name | Description |
---|---|
t |
The function type |
Example
This example shows how the objectFields
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import * from dw::core::Types
ns ns0 http://acme.com
type ADictionary = {_ : String}
type ASchema = {ns0#name @(ns0#foo: String): {}}
type AUser = {name @(foo?: String,l: Number)?: String, lastName*: Number}
---
{
a: objectFields(ADictionary),
b: objectFields(ASchema),
c: objectFields(Object),
d: objectFields(AUser)
}
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
{
"a": [
{
"key": {
"name": {
"localName": "_",
"namespace": null
},
"attributes": [
]
},
"required": true,
"repeated": false,
"value": "String"
}
],
"b": [
{
"key": {
"name": {
"localName": "name",
"namespace": "http://acme.com"
},
"attributes": [
{
"name": {
"localName": "foo",
"namespace": "http://acme.com"
},
"value": "String",
"required": true
}
]
},
"required": true,
"repeated": false,
"value": "Object"
}
],
"c": [
],
"d": [
{
"key": {
"name": {
"localName": "name",
"namespace": null
},
"attributes": [
{
"name": {
"localName": "foo",
"namespace": null
},
"value": "String",
"required": false
},
{
"name": {
"localName": "l",
"namespace": null
},
"value": "Number",
"required": true
}
]
},
"required": false,
"repeated": false,
"value": "String"
},
{
"key": {
"name": {
"localName": "lastName",
"namespace": null
},
"attributes": [
]
},
"required": true,
"repeated": true,
"value": "Number"
}
]
}
* ----
=== unionItems
==== unionItems(Type): Array<Type>
Returns an Array of all the Types the Union Type is defined with. It will fail if it is not an Union Type
_Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later._
===== Parameters
[%header, cols="1,3"]
|===
| Name | Description
| t | The type to be checked
|===
===== Example
This example shows how the `unionItems` behaves under different inputs.
====== Source
[source,DataWeave,linenums]
%dw 2.0 import * from dw::core::Types
type AType = String | Number output application/json --- { a: unionItems(AType) }
====== Output [source,Json,linenums]
{ "a": ["String","Number"] }
== Types === Attribute .Definition [source,DataWeave,linenums]
{ name: QName, required: Boolean, value: Type }
=== Field .Definition [source,DataWeave,linenums]
{ key: { name: QName, attributes: Array<Attribute> }, required: Boolean, repeated: Boolean, value: Type }
=== FunctionParam .Definition [source,DataWeave,linenums]
{ paramType: Type, optional: Boolean }
=== QName .Definition [source,DataWeave,linenums]
{ localName: String, namespace: Namespace | Null }
= dw::core::URL This module contains helper functions to work with Strings. To use this module, you must import it to your DataWeave code, for example, by adding the line `import * from dw::core::URL` to the header of your DataWeave script. == Functions === compose ==== compose(Array<String>, Array<String>): String Uses a custom interpolator to replace URL components with a `encodeURIComponent` result. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `parts` | A string array that provides the part of the URL to encode. |=== ===== Example This example passes in text to encode using `$(myText)`, where `myText` is a variable defined in the header. Notice that the spaces in the input are encoded in the output URL as `%20`. Also notice that the entire input to the `compose` function is surrounded by backticks. ====== Source [source,DataWeave, linenums]
%dw 2.0
import * from dw::core::URL
var myText = " text to encode "
output application/json
---
{ "composition" : compose http://asd/$(myText)/text
}
====== Output [source,JSON,linenums]
{ "composition": "http://asd/%20text%20to%20encode%20/text" }
=== decodeURI ==== decodeURI(String): String Decodes the escape sequences (such as `%20`) in a URI. The function 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. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `text` | The URI to decode. |=== ===== Example This example decodes a URI that contains the URL percent encoding `%20`, which is used for spaces. ====== Source [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::URL output application/json --- { "decodeURI" : decodeURI('http://asd/%20text%20to%20decode%20/text') }
====== Output [source,JSON,linenums]
{ "decodeURI": "http://asd/ text to decode /text" }
=== decodeURIComponent ==== decodeURIComponent(String): String Decodes a Uniform Resource Identifier (URI) component previously created by `encodeURIComponent` or a similar routine. For an example, see `encodeURIComponent`. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `text` | URI component string. |=== ===== Example This example decodes a variety of URI components. ====== Source [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::URL output application/json --- { "decodeURIComponent": { "decodeURIComponent" : decodeURIComponent("%20PATH/%20TO%20/DECODE%20"), "decodeURIComponent" : decodeURIComponent("%3B%2C%2F%3F%3A%40%26%3D"), "decodeURIComponent" : decodeURIComponent("%2D%5F%2E%21%7E%2A%27%28%29%24"), } }
====== Output [source,JSON,linenums]
{ decodeURIComponent: { decodeURIComponent: " PATH/ TO /DECODE ", decodeURIComponent: ";,/?:@&=", decodeURIComponent: "-_.!~*'()\$" } }
=== encodeURI ==== encodeURI(String): String Encodes a URI with UTF-8 escape sequences. Applies up to four escape sequences for characters composed of two "surrogate" characters. The function assumes that the URI is a complete URI, so it does not encode reserved characters that have special meaning. The function _does not encode these characters_ with UTF-8 escape sequences: [%header, cols="2,2"] |=== | Type (not escaped) | Examples | Reserved characters | ; , / ? : @ & = $ | Unescaped characters | alphabetic, decimal digits, - _ . ! ~ * ' ( ) | Number sign | # |=== ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `text` | The URI to encode. |=== ===== Example This example shows encodes spaces in one URL and lists some characters that do not get encoded in the `not_encoded` string. ====== Source [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::URL output application/json --- { "encodeURI" : encodeURI("http://asd/ text to decode /text"), "not_encoded": encodeURI("http://:;,/?:@&=\$-.!~*'()") }
====== Output [source,JSON,linenums]
{ "encodeURI": "http://asd/%20text%20to%20decode%20/%25/\"\'/text", "not_encoded": "http://:;,/?:@&=$-.!~*'()" }
=== encodeURIComponent ==== encodeURIComponent(String): String Escapes certain characters in a URI component using UTF-8 encoding. There can be only four escape sequences for characters composed of two "surrogate" * characters. `encodeURIComponent` escapes all characters _except the following_: alphabetic, decimal digits, `- _ . ! ~ * ' ( )`. Note that `encodeURIComponent` differs from `encodeURI` in that it encodes reserved characters and the Number sign `#` of `encodeURI`: [%header, cols="2,2"] |=== | Type | Includes | Reserved characters | | Unescaped characters | alphabetic, decimal digits, - _ . ! ~ * ' ( ) | Number sign | |=== ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `text` | URI component string. |=== ===== Example This example encodes a variety of URI components. ====== Source [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("-.!~'()") } }
====== Output [source,JSON,linenums]
{ "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": "-.!~'()" } }
=== parseURI ==== parseURI(String): URI Parses a URL and returns a `URI` object. The `isValid: Boolean` property in the output `URI` object indicates whether the parsing process succeeded. Every field in this object is optional, and a field will appear in the output only if it was present in the URL input. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `uri` | The URI input. |=== ===== Example This example parses a URL. ====== Source [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::URL output application/json --- { 'composition': parseURI('https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#footer') }
====== Output [source,JSON,linenums]
{ "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 Describes the URI type. For descriptions of the fields, see https://docs.mulesoft.com/mule-runtime/4.2/dataweave-types#dw_type_url[URL Types (dw::core::URL)]. .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::extension::DataFormat This module contains what is required for registering a new data format for the DataWeave language. For an example, see https://github.com/mulesoft-labs/data-weave-custom-data-format[Custom Data Formats Example]. == Types === DataFormat .Definition [source,DataWeave,linenums]
{ / * True if this is data format is represented in a binary representation instead of text, if not present is false / binaryFormat?: Boolean, / * The default charset of this format, if any. / defaultCharset?: String, / * Returns the list of file extensions with the . (".json", ".xml", etc…) that should be assigned to this Data Format / fileExtensions?: Array<String>, / * The list of MimeTypes that are accepted / acceptedMimeTypes: Array<MimeType>, / * This function will be in charge of reading the raw content and transform it into the DW canonical model / reader: (content: Binary, charset: String, settings: ReaderSettings) → Any, / * This function will be in charge of writing the DW canonical model into Binary content / writer: (value: Any, settings: WriterSettings) → Binary }
=== EmptySettings .Definition [source,DataWeave,linenums]
Object
=== EncodingSettings .Definition [source,DataWeave,linenums]
{ / * Encoding to be used by this writer. / encoding?: String }
=== MimeType .Definition [source,DataWeave,linenums]
String
=== Settings .Definition [source,DataWeave,linenums]
Object
== Annotations = dw::module::Multipart This helper module provide functions for creating MultiPart and formats and parts (including fields and boundaries) of MultiPart formats. To use this module, you must import it into your DataWeave code, for example, by adding the line `import dw::module::Multipart` to the header of your DataWeave script. == Functions === field ==== field({| name: String, value: Any, mime?: String, fileName?: String |}): MultipartPart Creates a `MultipartPart` data structure using the specified part name, input content for the part, format (or mime type), and optionally, file name. This version of the `field` function accepts arguments as an array of objects that use the parameter names as keys, for example: `Multipart::field({name:"order",value: myOrder, mime: "application/json", fileName: "order.json"})` ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `opts` a| Array of objects that specifies: * A unique `name` (required) for the `Content-Disposition` header of the part. * A `value` (required) for the content of the part. * `mime` (optional for strings) for the mime type (for example, `application/json`) to apply to content within the part. This setting can be used to transform the input type, for example, from JSON to XML. * An optional `fileName` value that you can supply to the `filename` parameter in the part's `Content-Disposition` header. |=== ===== Example This example produces two parts. The first part (named `order`) outputs content in JSON and provides a file name for the part (`order.json`). The second (named `clients`) outputs content in XML and does not provide a file name. Also notice that in this example you need to add the function's namespace to the function name, for example, `Multipart::field`. ====== Source [source,DataWeave,linenums]
%dw 2.0 import dw::module::Multipart output multipart/form-data var myOrder = [ { order: 1, amount: 2 }, { order: 32, amount: 1 } ] var myClients = { clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } } } --- { parts: { order: Multipart::field({name:"order",value: myOrder, mime: "application/json", fileName: "order.json"}), clients: Multipart::field({name:"clients", value: myClients, mime: "application/xml"}) } }
====== Output [source,txt,linenums]
------=_Part_8032_681891620.1542560124825 Content-Type: application/json Content-Disposition: form-data; name="order"; filename="order.json"
[ { "order": 1, "amount": 2 }, { "order": 32, "amount": 1 } ] ------=_Part_8032_681891620.1542560124825 Content-Type: application/xml Content-Disposition: form-data; name="clients"
<clients> <client> <id>1</id> <name>Mariano</name> </client> <client> <id>2</id> <name>Shoki</name> </client> </clients> ------=_Part_8032_681891620.1542560124825--
==== field(String, Any, String, String): MultipartPart Creates a `MultipartPart` data structure using the specified part name, input content for the part, format (or mime type), and optionally, file name. This version of the `field` function accepts arguments in a comma-separated list, for example: [source,txt,linenums]
Multipart::field("order", myOrder,"application/json", "order.json")`
===== Parameters [%header, cols="1,3"] |=== | Name | Description | `opts` a| A set of parameters that specify: * A unique `name` (required) for the `Content-Disposition` header of the part. * A `value` (required) for the content of the part. * `mime` (optional for strings) for the mime type (for example, `application/json`) to apply to content within the part. This type can be used to transform the input type. * An optional `fileName` value that you can supply to the `filename` parameter in the part's `Content-Disposition` header. |=== ===== Example This example produces two parts. The first part (named `order`) outputs content in JSON and provides a file name for the part (`order.json`). The second (named `clients`) outputs content in XML and does not provide a file name. The only difference between this `field` example and the previous `field` example is the way you pass in arguments to the method. Also notice that in this example you need to add the function's namespace to the function name, for example, `Multipart::field`. ====== Source [source,DataWeave,linenums]
%dw 2.0 import dw::module::Multipart output multipart/form-data var myOrder = [ { order: 1, amount: 2 }, { order: 32, amount: 1 } ] var myClients = { clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } } } --- { parts: { order: Multipart::field("order", myOrder, "application/json", "order.json"), clients: Multipart::field("clients", myClients, "application/xml") } }
====== Output [source,txt,linenums]
------=_Part_4846_2022598837.1542560230901 Content-Type: application/json Content-Disposition: form-data; name="order"; filename="order.json"
[ { "order": 1, "amount": 2 }, { "order": 32, "amount": 1 } ] ------=_Part_4846_2022598837.1542560230901 Content-Type: application/xml Content-Disposition: form-data; name="clients"
<clients> <client> <id>1</id> <name>Mariano</name> </client> <client> <id>2</id> <name>Shoki</name> </client> </clients> ------=_Part_4846_2022598837.1542560230901--
=== file ==== file({| name: String, path: String, mime?: String, fileName?: String |}) Creates a `MultipartPart` data structure from a resource file. This version of the `file` function accepts arguments as an array of objects that use the parameter names as keys, for example: [source,txt,linenums]
Multipart::file({ name: "myFile", path: "myClients.json", mime: "application/json", fileName: "partMyClients.json"})
===== Parameters [%header, cols="1,3"] |=== | Name | Description | `opts` a| Array of objects that specifies: * A unique `name` (required) for the `Content-Disposition` header of the part. * A `path` (required) relative to the `src/main/resources` project path for the Mule app. * `mime` (optional for strings) for the mime type (for example, `application/json`) to apply to content within the part. This setting _cannot_ be used to transform the input mime type. * An optional `fileName` value for the `filename` parameter in the part's `Content-Disposition` header. Defaults to the string `"filename"` if not supplied. This value does not need to match the input file name. |=== ===== Example This example inserts file content from a `MultipartPart` into a `Multipart` data structure. It uses the `form` function to create the `Multipart` and uses `file` to create a part named `myClient` with JSON content from an external file `myClients.json`. It also specifies `partMyClients.json` as the value for to the `filename` parameter. ====== Source [source,DataWeave,linenums]
%dw 2.0 import dw::module::Multipart output multipart/form-data var myClients = "myClients.json" var myArgs = { name: "myFile", path: "myClients.json", mime: "application/json", * fileName: "partMyClients.json"} --- Multipart::form([ Multipart::file(myArgs) ])
====== Input A file called `myClients.json` and located in `src/main/resources` with the following content. [source,json,linenums]
clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } }
====== Output [source,txt,linenums]
------=_Part_1586_1887987980.1542569342438 Content-Type: application/json Content-Disposition: form-data; name="myFile"; filename="partMyClients.json"
{ clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } } } ------=_Part_1586_1887987980.1542569342438--
==== file(String, String, String, String) Creates a `MultipartPart` data structure from a resource file. This version of the `file` function accepts arguments in a comma-separated list, for example: [source,txt,linenums]
Multipart::field("myFile", myClients, 'application/json', "partMyClients.json")
===== Parameters [%header, cols="1,3"] |=== | Name | Description | `opts` a| Array of objects that specifies: * A unique `name` (required) for the `Content-Disposition` header of the part. * A `path` (required) relative to the `src/main/resources` project path for the Mule app. * `mime` (optional for strings) for the mime type (for example, `application/json`) to apply to content within the part. This setting _cannot_ be used to transform the input mime type. * An optional `fileName` value for the `filename` parameter in the part's `Content-Disposition` header. Defaults to the string `"filename"` if not supplied. This value does not need to match the input file name. |=== ===== Example This example inserts file content from a `MultipartPart` into a `Multipart` data structure. It uses the `form` function to create the `Multipart` type and uses `file` to create a part named `myClient` with JSON content from an external file `myClients.json`. It also specifies `partMyClients.json` as the value for to the `filename` parameter. ====== Source [source,DataWeave,linenums]
%dw 2.0 import dw::module::Multipart var myClients = "myClients.json" output multipart/form-data --- Multipart::form([ Multipart::file("myFile", myClients, 'application/json', "partMyClients.json") ])
====== Input A file called `myClients.json` and located in `src/main/resources` with the following content. [source,JSON,linenums]
clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } }
====== Output [source,txt,linenums]
------=_Part_1586_1887987980.1542569342438 Content-Type: application/json Content-Disposition: form-data; name="myFile"; filename="partMyClients.json"
{ clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } } } ------=_Part_1586_1887987980.1542569342438--
=== form ==== form(Array<MultipartPart>): Multipart Creates a `Multipart` data structure using a specified array of parts. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `parts` | An array of parts (`MultipartPart` data structures). |=== ===== Example This example creates a `Multipart` data structure that contains parts, which are described in examples for the `field` function. For additional uses of `form`, see examples in the Multipart `file` and `field` https://docs.mulesoft.com/mule-runtime/4.2/dw-multipart-functions-form[documentation]. ====== Source [source,DataWeave,linenums]
%dw 2.0 import dw::module::Multipart output multipart/form-data var firstPart = "content for my first part" var secondPart = "content for my second part" --- { parts: { part1: Multipart::field({name:"myFirstPart",value: firstPart}), part2: Multipart::field("mySecondPart", secondPart) } }
====== Output [source,txt,linenums]
------=_Part_320_1528378161.1542639222352 Content-Disposition: form-data; name="myFirstPart"
content for my first part ------=_Part_320_1528378161.1542639222352 Content-Disposition: form-data; name="mySecondPart"
content for my second part ------=_Part_320_1528378161.1542639222352--
=== generateBoundary ==== generateBoundary(Number): String Helper function for generating boundaries in `Multipart` data structures. == Types === Multipart `MultiPart` type, a data structure for a complete `Multipart` format. See the output example for the Multipart `form` function https://docs.mulesoft.com/mule-runtime/4.2/dw-multipart-functions-form[documentation]. .Definition [source,DataWeave,linenums]
{ preamble?: String, parts: { _?: MultipartPart } }
=== MultipartPart `MultipartPart` type, a data structure for a part within a `MultiPart` format. See the output examples for the Multipart `field` function https://docs.mulesoft.com/mule-runtime/4.2/dw-multipart-functions-field[documentation]. .Definition [source,DataWeave,linenums]
{ headers?: { "Content-Disposition"?: { name: String, filename?: String }, "Content-Type"?: String }, content: Any }
= dw::util::Diff This utility module calculates the difference between two values and returns the list of differences. The module is included with Mule runtime. To use it, you must import it to your DataWeave code, for example, by adding the line `import dw::util::Diff` or `import * from dw::util::Diff` to your header. == Functions === diff ==== diff(Any, Any, { unordered?: Boolean }, String): Diff Returns the structural differences between two values. Differences between objects can be ordered (the default) or unordered. Ordered means that two objects do not differ if their key-value pairs are in the same order. Differences are expressed as `Difference` type. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `actual` | The actual value. Can be any data type. | `expected` | The expected value to compare to the actual. Can be any data type. | `diffConfig` | Setting for changing the default to unordered using `{ "unordered" : true} (explained in the introduction). |=== ===== Example This example shows a variety of uses of `diff`. ====== Source [source,Dataweave, linenums]
import diff from dw::util::Diff ns ns0 http://locahost.com ns ns1 http://acme.com output application/dw --- { "a": diff({a: 1}, {b:1}), "b": diff({ns0#a: 1}, {ns1#a:1}), "c": diff([1,2,3], []), "d": diff([], [1,2,3]), "e": diff([1,2,3], [1,2,3, 4]), "f": diff([{a: 1}], [{a: 2}]), "g": diff({a @(c: 2): 1}, {a @(c: 3): 1}), "h": diff(true, false), "i": diff(1, 2), "j": diff("test", "other test"), "k": diff({a: 1}, {a:1}), "l": diff({ns0#a: 1}, {ns0#a:1}), "m": diff([1,2,3], [1,2,3]), "n": diff([], []), "o": diff([{a: 1}], [{a: 1}]), "p": diff({a @(c: 2): 1}, {a @(c:2): 1}), "q": diff(true, true), "r": diff(1, 1), "s": diff("other test", "other test"), "t": diff({a:1 ,b: 2},{b: 2, a:1}, {unordered: true}), "u": [{format: "ssn",data: "ABC"}] diff [{ format: "ssn",data: "ABC"}] }
====== Output [source,XML,linenums]
ns ns0 http://locahost.com ns ns1 http://acme.com --- { a: { matches: false, diffs: [ { expected: "Entry (root).a with type Number", actual: "was not present in object.", path: "(root).a" } ] }, b: { matches: false, diffs: [ { expected: "Entry (root).ns0#a with type Number", actual: "was not present in object.", path: "(root).ns0#a" } ] }, c: { matches: false, diffs: [ { expected: "Array size is 0", actual: "was 3", path: "(root)" } ] }, d: { matches: false, diffs: [ { expected: "Array size is 3", actual: "was 0", path: "(root)" } ] }, e: { matches: false, diffs: [ { expected: "Array size is 4", actual: "was 3", path: "(root)" } ] }, f: { matches: false, diffs: [ { expected: "1" as String {mimeType: "application/dw"}, actual: "2" as String {mimeType: "application/dw"}, path: "(root)[0].a" } ] }, g: { matches: false, diffs: [ { expected: "3" as String {mimeType: "application/dw"}, actual: "2" as String {mimeType: "application/dw"}, path: "(root).a.@.c" } ] }, h: { matches: false, diffs: [ { expected: "false", actual: "true", path: "(root)" } ] }, i: { matches: false, diffs: [ { expected: "2", actual: "1", path: "(root)" } ] }, j: { matches: false, diffs: [ { expected: "\"other test\"", actual: "\"test\"", path: "(root)" } ] }, k: { matches: true, diffs: [] }, l: { matches: true, diffs: [] }, m: { matches: true, diffs: [] }, n: { matches: true, diffs: [] }, o: { matches: true, diffs: [] }, p: { matches: true, diffs: [] }, q: { matches: true, diffs: [] }, r: { matches: true, diffs: [] }, s: { matches: true, diffs: [] }, t: { matches: true, diffs: [] }, u: { matches: true, diffs: [] } }
== Types === Diff Describes the entire difference between two values. *Example with no differences*: `{ "matches": true, "diffs": [ ] }` *Example with differences*: `{ "matches": true, "diffs": [ "expected": "4", "actual": "2", "path": "(root).a.@.d" ] }` See the `diff` function for another example. .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 This is a utility module. The module is included with Mule runtime. To use it, you must import it into your DataWeave code, for example, by adding the line `import * from dw::util::Timer` to the header of your script. == Functions === currentMilliseconds ==== currentMilliseconds(): Number Returns the current time in milliseconds. ===== Example This example shows the time in milliseconds when the function executed. ====== Source [source,Dataweave, linenums]
%dw 2.0 import * from dw::util::Timer output application/json --- { "currentMilliseconds" : currentMilliseconds() }
====== Output [source,XML,linenums]
{ "currentMilliseconds": 1532923168900 }
=== duration ==== duration(() -> T): DurationMeasurement<T> Executes the input function and returns an object with execution time in milliseconds and result of that function. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `valueToMeasure` | A function to pass to `duration`. |=== ===== Example This example passes a `wait` function (defined in the header), which returns the execution time and result of that function in a `DurationMeasurement` object. ====== Source [source,Dataweave, linenums]
%dw 2.0 output application/json fun myFunction() = dw::Runtime::wait("My result",100) --- dw::util::Timer::duration) → myFunction(
====== Output [source,XML,linenums]
{ "time": 101, "result": "My result" }
=== time ==== time(() -> T): TimeMeasurement<T> Executes the input function and returns a `TimeMeasurement` object that contains the start and end time for the execution of that function, as well the result of the function. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `valueToMeasure` | A function to pass to `time`. |=== ===== Example This example passes `wait` and `sum` functions (defined in the header), which return their results in `TimeMeasurement` objects. [source,Dataweave, linenums]
%dw 2.0 output application/json fun myFunction() = dw::Runtime::wait("My result",100) fun myFunction2() = sum([1,2,3,4]) --- { testing: [ dw::util::Timer::time) → myFunction(, dw::util::Timer::time) → myFunction2( ] }
====== Output [source,XML,linenums]
{ "testing": [ { "start": "2018-10-05T19:23:01.49Z", "result": "My result", "end": "2018-10-05T19:23:01.591Z" }, { "start": "2018-10-05T19:23:01.591Z", "result": 10, "end": "2018-10-05T19:23:01.591Z" } ] }
=== toMilliseconds ==== toMilliseconds(DateTime): Number Returns the representation of a specified date-time in milliseconds. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `date` | A `DateTime` to evaluate. |=== ===== Example This example shows a date-time in milliseconds. ====== Source [source,Dataweave, linenums]
%dw 2.0 import * from dw::util::Timer output application/json --- { "toMilliseconds" : toMilliseconds(|2018-07-23T22:03:04.829Z|) }
====== Output [source,XML,linenums]
{ "toMilliseconds": 1532383384829 }
== Types === DurationMeasurement A return type that contains the execution time and result of a function call. .Definition [source,DataWeave,linenums]
{ time: Number, result: T }
=== TimeMeasurement A return type that contains a start time, end time, and result of a function call. .Definition [source,DataWeave,linenums]
{ start: DateTime, result: T, end: DateTime }
= dw::util::Tree This utility module provides functions that enable you to handle values as though they are tree data structures. The module is included with Mule runtime. To use it, you must import it into your DataWeave code, for example, by adding the line `import * from dw::util::Tree` to the header of your script. _Introduced in DataWeave 2.2.2. Supported by Mule 4.2.2 and later._ == Functions === asExpressionString ==== asExpressionString(Path): String Transforms a path to a string representation. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | path | The path to transform to a string. |=== ===== Example This example transforms a path to a string representation. ====== Source [source,DataWeave,linenums]
%dw 2.0 import * from dw::util::Tree output application/json --- asExpressionString([{kind: OBJECT_TYPE, selector: "user", namespace: null}, {kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}])
====== Output [source,Json,linenums]
".user.@name"
=== mapLeafValues ==== mapLeafValues(Any, (value: Any, path: Path) -> Any): Any Maps the terminal (leaf) nodes in the tree. Leafs nodes cannot have an object or an array as a value. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `value` | The value to map. | `callback` | The mapper function. |=== ===== Example This example transforms all the string values to upper case. ====== Source [source,DataWeave,linenums]
%dw 2.0 output application/json --- %dw 2.0 import * from dw::util::Tree output application/json --- { user: [{ name: "mariano", lastName: "achaval" }], group: "data-weave" } mapLeafValues (value, path) → upper(value)
====== Output [source,Json,linenums]
{ "user": [ { "name": "MARIANO", "lastName": "ACHAVAL" } ], "group": "DATA-WEAVE" }
=== nodeExists ==== nodeExists(Any, (value: Any, path: Path) -> Boolean): Boolean Returns `true` if any node in the tree validates against the specified criteria. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `value` | The value to search. | `callback` | The criteria. |=== ===== Example This example checks for any user with the name `peter`. ====== Source [source,DataWeave,linenums]
%dw 2.0 output application/json --- * %dw 2.0 import * from dw::util::Tree output application/json --- { user: [{ name: "mariano", lastName: "achaval", friends: [ { name: "julian" }, { name: "tom" } ] }, { name: "leandro", lastName: "shokida", friends: [ { name: "peter" }, { name: "robert" } ]
} ],
} nodeExists ((value, path) -> path[-1].selector == "name" and value == "peter")
====== Output [source,Json,linenums]
11.2. true
11.3. Variables
11.3.1. ARRAY_TYPE
11.3.2. ATTRIBUTE_TYPE
11.3.3. OBJECT_TYPE
11.4. Types
11.4.1. Path
Represents an array of PathElement
types that identify the location of a node in a tree.
1
Array<PathElement>
11.4.2. PathElement
Represents a specific selection of a node in a path.
1
2
{| // {options: ["Object","Attribute","Array"]}
kind: String, selector: String | Number, namespace: Namespace | Null |}
12. dw::util::Values
This utility module simplifies changes to values.
The module is included with Mule runtime. To use it, you must import it into
your DataWeave code, for example, by adding the line
import * from dw::util::Values
to the header of your script.
Introduced in DataWeave 2.2.2. Supported by Mule 4.2.2 and later.
12.1. Functions
12.1.1. attr
attr(Namespace | Null, String): PathElement
This function creates a PathElement
to use for selecting an XML
attribute and populates the type’s selector
field with the given string.
Some versions of the update
and mask
functions accept a PathElement
as
an argument.
Parameters
Name | Description |
---|---|
|
The namespace of the attribute to select. If not specified, a null value is set. |
|
The string that names the attribute to select. |
Example
This example creates an attribute selector for a specified namespace
(ns0
) and sets the selector’s value to "myAttr"
. In the
output, also note that the value of the "kind"
key is "Attribute"
.
1
2
3
4
5
6
%dw 2.0
output application/json
import * from dw::util::Values
ns ns0 http://acme.com/fo
---
attr(ns0 , "myAttr")
1
2
3
4
5
{
"kind": "Attribute",
"namespace": "http://acme.com/foo",
"selector": "myAttr"
}
12.1.2. field
field(Namespace | Null, String): PathElement
This function creates a PathElement
data type to use for selecting an
object field and populates the type’s selector
field with the given
string.
Some versions of the update
and mask
functions accept a PathElement
as
an argument.
Parameters
Name | Description |
---|---|
|
The namespace of the field to select. If not specified, a null value is set. |
|
A string that names the attribute to select. |
Example
This example creates an object field selector for a specified namespace
(ns0
) and sets the selector’s value to "myFieldName"
. In the
output, also note that the value of the "kind"
key is "Object"
.
1
2
3
4
5
6
%dw 2.0
output application/json
import * from dw::util::Values
ns ns0 http://acme.com/foo
---
field(ns0 , "myFieldName")
1
2
3
4
5
{
"kind": "Object",
"namespace": "http://acme.com/foo",
"selector": "myFieldName"
}
12.1.3. index
index(Number): PathElement
This function creates a PathElement
data type to use for selecting an
array element and populates the type’s selector
field with the specified
index.
Some versions of the update
and mask
functions accept a PathElement
as
an argument.
Parameters
Name | Description |
---|---|
|
The index. |
Example
This example creates an selector for a specified index.
It sets the selector’s value to 0
. In the
output, also note that the value of the "kind"
key is "Array"
.
1
2
3
4
5
6
%dw 2.0
output application/json
import * from dw::util::Values
ns ns0 http://acme.com/foo
---
index(0)
1
2
3
4
5
{
"kind": "Array",
"namespace": null,
"selector": 0
}
12.1.4. mask
mask(Null, String | Number | PathElement): Any
Helper function that makes mask
work correctly with null
.
mask(Any, PathElement): Any
This mask
function replaces all simple elements that match the specified
criteria.
Simple elements do not have child elements and cannot be objects or arrays.
Parameters
Name | Description |
---|---|
|
A value to use for masking. The value can be any DataWeave type. |
|
The |
Example
This example shows how to mask the value of a password
field in
an array of objects. It uses field("password")
to return the PathElement
that it passes to mask
. It uses with ""
to specify the value
() to use for masking.
1
2
3
4
5
%dw 2.0
output application/json
import * from dw::util::Values
---
[{name: "Peter Parker", password: "spiderman"}, {name: "Bruce Wayne", password: "batman"}] mask field("password") with "*****"
1
2
3
4
5
6
7
8
9
10
[
{
"name": "Peter Parker",
"password": "*****"
},
{
"name": "Bruce Wayne",
"password": "*****"
}
]
mask(Any, String): Any
This mask
function selects a field by its name.
Parameters
Name | Description |
---|---|
|
The value to use for masking. The value can be any DataWeave type. |
|
A string that specifies the name of the field to mask. |
Example
This example shows how to perform masking using the name of a field in the input. It modifies the values of all fields with that value.
1
2
3
4
5
%dw 2.0
output application/json
import * from dw::util::Values
---
[{name: "Peter Parker", password: "spiderman"}, {name: "Bruce Wayne", password: "batman"}] mask "password" with "*****"
1
2
3
4
5
6
7
8
9
10
[
{
"name": "Peter Parker",
"password": "*****"
},
{
"name": "Bruce Wayne",
"password": "*****"
}
]
mask(Any, Number): Any
This mask
function selects an element from array by its index.
Parameters
Name | Description |
---|---|
|
The value to mask. The value can be any DataWeave type. |
|
The index to mask. The index must be a number. |
Example
This example shows how mask
acts on all elements in the nested arrays.
It changes the value of each element at index 1
to false
.
1
2
3
4
5
%dw 2.0
output application/json
import * from dw::util::Values
---
[[123, true], [456, true]] mask 1 with false
1
2
3
4
5
6
7
8
9
10
[
[
123,
false
],
[
456,
false
]
]
12.1.5. update
update(Object, String): Any
This update
function updates a field in an object with the specified
string value.
The function returns a new object with the specified field and value.
Parameters
Name | Description |
---|---|
|
The object to update. |
|
A string that provides the name of the field. |
Example
This example updates the name
field in the object {name: "Mariano"}
with
the specified value.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
{name: "Mariano"} update "name" with "Data Weave"
1
2
3
{
"name": "Data Weave"
}
update(Object, PathElement): Any
This update
function updates an object field with the specified
PathElement
value.
The function returns a new object with the specified field and value.
Parameters
Name | Description |
---|---|
|
The object to update. |
|
A |
Example
This example updates the value of a name
field in the object
{name: "Mariano"}
. It uses field("name")
to return the PathElement
that it passes to update
. It uses with "Data Weave"
to specify the value
(Data Weave
) of name
.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
{name: "Mariano"} update field("name") with "Data Weave"
1
2
3
{
"name": "Data Weave"
}
update(Array, Number): Any
Updates an array index with the specified value.
This update
function returns a new array that changes the value of
the specified index.
Parameters
Name | Description |
---|---|
objectValue |
The array to update. |
indexToUpdate |
The index of the array to update. The index must be a number. |
Example
This example replaces the value 2
(the index is 1
) with 5
in the
the input array [1,2,3]
.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
[1,2,3] update 1 with 5
1
2
3
4
5
6
[
1,
5,
3
]
update(Array, String): Any
This update
function updates all objects within the specified array with
the given string value.
Parameters
Name | Description |
---|---|
|
The array of objects to update. |
|
A string providing the name of the field to update. |
Example
This example updates value of the role
fields in the array of objects.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
[{role: "a", name: "spiderman"}, {role: "b", name: "batman"}] update "role" with "Super Hero"
1
2
3
4
5
6
7
8
9
[{
"role": "Super Hero",
"name": "spiderman"
},
{
"role": "Super Hero",
"name": "batman"
}]
update(Array, PathElement): Any
This update
function updates the specified index of an array with the
given PathElement
value.
The function returns a new array that contains given value at the specified index.
Parameters
Name | Description |
---|---|
|
The array to update. |
|
The index of the array to update. The index must be specified as a |
Example
This example updates the value of an element in the input array. Notice
that it uses index(1)
to return the index as a PathElement
, which
it passes to update
. It replaces the value 2
at that index with 5
.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
[1,2,3] update index(1) with 5
1
2
3
4
5
6
[
1,
5,
3
]
update(Array | Object | Null, Array<String | Number | PathElement>): Any
Updates the value at the specified path with the given value.
Parameters
Name | Description |
---|---|
|
The value to update. Accepts an array, object, or null value. |
|
The path to update. The path must be an array of strings, numbers, or `PathElement`s. |
Example
This example updates the name of the user.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
{user: {name: "Mariano"}} update ["user", field("name")] with "Data Weave"
1
2
3
4
5
6
{
"user": {
"name": "Data Weave"
}
}
update(Null, Number | String | PathElement): Any
Helper function to make update
null friendly.