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 enables distinctBy to work with a null value.
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 object to describe. |
Example
This example returns the key, value, and attributes from the object specified
in the variable myVar. The object is the XML input to the read function.
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
---
{ "entriesOf" : entriesOf(myVar) }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"entriesOf": [
{
"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 the users with age bigger or equal to 30. It shows that inside the filter lambda, the data of each element can be access.
1
2
3
4
%dw 2.0
---
[{name: "Mariano", age: 37}, {name: "Shoki", age: 30}, {name: "Tomo", age: 25}, {name: "Ana", age: 29}]
filter ((value, index) -> value.age >= 30)
1
2
3
4
5
6
7
8
9
10
[
{
"name": "Mariano",
"age": 37
},
{
"name": "Shoki",
"age": 30
}
]
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 enables filter to work with a null value.
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 enables filterObject to work with a null value.
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 enables flatMap to work with a null value.
1.1.15. flatten
flatten(Array<Array<T> | Q>): Array<T | Q>
Turns a set of subarrays (such as [ [1,2,3], [4,5,[6]], [], [null] ]) into a single, flattened array (such as [ 1, 2, 3, 4, 5, [6], null ]).
Note that it flattens only the first level of subarrays and omits empty subarrays.
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 enables flatten to work with a null value.
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 enables groupBy to work with a null value.
1.1.18. isBlank
isBlank(String | Null): Boolean
Returns true if the given string is empty (""), completely composed of whitespaces, or null. Otherwise, the function returns false.
Parameters
| Name | Description |
|---|---|
|
An 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.
The ! operator is supported starting in Dataweave 2.2.0. Use ! only in Mule 4.2 and later versions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
%dw 2.0
output application/json
var someString = "something"
var nullString = null
---
{
// checking if the string is blank
"emptyString" : isBlank(""),
"stringWithSpaces" : isBlank(" "),
"textString" : isBlank(someString),
"somePayloadValue" : isBlank(payload.nonExistingValue),
"nullString" : isBlank(nullString),
// checking if the string is not blank
"notEmptyTextString" : not isBlank(" 1234"),
"notEmptyTextStringTwo" : ! isBlank("")
}
1
2
3
4
5
6
7
8
9
{
"emptyString": true,
"stringWithSpaces": true,
"textString": false,
"somePayloadValue": true,
"nullString": true,
"notEmptyTextString": true,
"notEmptyTextStringTwo": false
}
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 for different values. Note numbers within strings get coerced to numbers.
1
2
3
4
%dw 2.0
output application/json
---
[isInteger(1), isInteger(2.0), isInteger(2.2), isInteger("1")]
1
[ true, true, false, 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 key-value pairs within the input 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 key-value pairs within the input object.
1
2
3
4
%dw 2.0
output application/json
---
{ "keysOf" : keysOf({ "a" : true, "b" : 1}) }
1
{ "keysOf" : ["a","b"] }
Example
This example illustrates a difference between keysOf and namesOf.
Notice that keysOf retains the attributes (name and lastName)
and namespaces (xmlns) from the XML input, while namesOf 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
---
{ keysOfExample: flatten([keysOf(myVar.users) map $.#,
keysOf(myVar.users) map $.@])
}
++
{ namesOfExample: 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
{
"keysOfExample": [
"http://test.com",
"http://test.com",
{
"name": "Mariano",
"lastName": "Achaval"
},
{
"name": "Stacey",
"lastName": "Duke"
}
],
"namesOfExample": [
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. So this makes it very simple to debug your code, because any expression or subexpression can be wrapped
with log and the result will be printed out without modifying the result of the expression.
The output is going to be printed in application/dw format.
The prefix parameter is optional and allows to easily find the log output.
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("User", myUser.user).friend.name
1
WARNING - "Houston, we have a problem."
Example
This example shows how to log the result of myUser.user expression without the need of modifying the original expression myUser.user.friend.name.
1
2
3
4
5
6
%dw 2.0
output application/json
var myUser = {user: {friend: {name: "Shoki"}, id: 1, name: "Tomo"}, accountId: "leansh" }
---
log("User", myUser.user).friend.name
User - {
friend: {
name: "Shoki"
},
id: 1,
name: "Tomo"
}
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 enables lower to work with a null value.
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 enables map to work with a null value.
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 enables mapObject to work with a null value.
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 must be of the same type. maxBy throws an error if they are not,
and the function returns null if 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 must be of the same type or min 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 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 the names of all the keys within 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 key-value pairs within 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. 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.40. 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 enables orderBy to work with a null value.
1.1.41. 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 enables pluck to work with a null value.
1.1.42. 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.43. 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.44. 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.45. 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 Supported Data Formats. |
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.46. readUrl
readUrl(String, String, Object): Any
Reads a URL, including a classpath-based URL, and returns parsed content.
This function works similar to the read function.
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. Other than the URL, 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 Supported Data Formats. |
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 CSV file from a URL, sets reader properties to indicate that there’s no header, and then transforms the data to JSON.
1
2
3
4
%dw 2.0
output application/json
---
readUrl("https://mywebsite.com/data.csv", "application/csv", {"header" : false})
Max,the Mule,MuleSoft
1
2
3
4
5
6
7
[
{
"column_0": "Max",
"column_1": "the Mule",
"column_2": "MuleSoft"
}
]
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.47. 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.48. 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.49. 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.50. 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.51. 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.52. 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.53. 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.54. 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.55. 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.56. 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.57. 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 enables trim to work with a null value.
1.1.58. 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.59. 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.60. 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 enables upper to work with a null value.
1.1.61. 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.62. 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 of key-value pairs within 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.63. with
with(((V, U) → R) → X, (V, U) → R): X
Helper function that specifies a replacement element. This function is used with replace, update or mask to perform data substitutions.
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. The replace function specifies the base string and a regex to select the characters to replace, and with provides the replacement string to use.
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.64. 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 Supported Data Formats. |
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.65. 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.66. 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. |
|
The MD5 message digest algorithm as defined in RFC 1321. |
|
Hash algorithms defined in the FIPS PUB 180-2. 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. dataFormatsDescriptor
dataFormatsDescriptor(): Array<DataFormatDescriptor>
Returns the description of all the DataFormats that are installed in the current Runtime
Example
This example shows how the dataFormatsDescriptor behaves under different inputs.
1
2
3
import * from dw::Runtime
---
dataFormatsDescriptor()
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
[
{
"id": "json",
"binary": false,
"defaultEncoding": "UTF-8",
"extensions": [
".json"
],
"defaultMimeType": "application/json",
"acceptedMimeTypes": [
"application/json"
],
"readerProperties": [
{
"name": "streaming",
"optional": true,
"defaultValue": false,
"description": "Used for streaming input (use only if entries are accessed sequentially).",
"possibleValues": [
true,
false
]
}
],
"writerProperties": [
{
"name": "writeAttributes",
"optional": true,
"defaultValue": false,
"description": "Indicates that if a key has attributes, they are going to be added as children key-value pairs of the key that contains them. The attribute new key name will start with @.",
"possibleValues": [
true,
false
]
},
{
"name": "skipNullOn",
"optional": true,
"defaultValue": "None",
"description": "Indicates where is should skips null values if any or not. By default it doesn't skip.",
"possibleValues": [
"arrays",
"objects",
"everywhere"
]
}
]
},
{
"id": "xml",
"binary": false,
"extensions": [
".xml"
],
"defaultMimeType": "application/xml",
"acceptedMimeTypes": [
"application/xml"
],
"readerProperties": [
{
"name": "supportDtd",
"optional": true,
"defaultValue": true,
"description": "Whether DTD handling is enabled or disabled; disabling means both internal and external subsets will just be skipped unprocessed.",
"possibleValues": [
true,
false
]
},
{
"name": "streaming",
"optional": true,
"defaultValue": false,
"description": "Used for streaming input (use only if entries are accessed sequentially).",
"possibleValues": [
true,
false
]
},
{
"name": "maxEntityCount",
"optional": true,
"defaultValue": 1,
"description": "The maximum number of entity expansions. The limit is in place to avoid Billion Laughs attacks.",
"possibleValues": [
]
}
],
"writerProperties": [
{
"name": "writeDeclaration",
"optional": true,
"defaultValue": true,
"description": "Indicates whether to write the XML header declaration or not.",
"possibleValues": [
true,
false
]
},
{
"name": "indent",
"optional": true,
"defaultValue": true,
"description": "Indicates whether to indent the code for better readability or to compress it into a single line.",
"possibleValues": [
true,
false
]
}
]
}
]
3.1.2. eval
eval(String, Dictionary<String>, Dictionary<ReaderInput>, Dictionary<Any>, RuntimeExecutionConfiguration): EvalSuccess | ExecutionFailure
EXPERIMENTAL
Evaluates a given script with the specified context and returns the result of that evaluation
Parameters
| Name | Description |
|---|---|
fileToExecute |
The name of the file to execute |
fs |
An Object with the files |
readerInputs |
The reader inputs to bind |
inputValues |
Additional literal values to bind |
configuration |
Runtime configuration |
Example
This example shows how the eval behaves under different inputs.
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
%dw 2.0
import * from dw::Runtime
var jsonValue = {
value: '{"name": "Mariano"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var jsonValue2 = {
value: '{"name": "Mariano", "lastName": "achaval"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var invalidJsonValue = {
value: '{"name": "Mariano' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var Utils = "fun sum(a,b) = a +b"
output application/json
---
{
"execute_ok" : run("main.dwl", {"main.dwl": "{a: 1}"}, {"payload": jsonValue }),
"logs" : do {
var execResult = run("main.dwl", {"main.dwl": "{a: log(1)}"}, {"payload": jsonValue })
---
{
m: execResult.logs.message,
l: execResult.logs.level
}
},
"grant" : eval("main.dwl", {"main.dwl": "{a: readUrl(`http://google.com`)}"}, {"payload": jsonValue }, {},{ securityManager: (grant, args) -> false }),
"library" : eval("main.dwl", {"main.dwl": "Utils::sum(1,2)", "/Utils.dwl": Utils }, {"payload": jsonValue }),
"timeout" : eval("main.dwl", {"main.dwl": "(1 to 1000000000000) map \$ + 1" }, {"payload": jsonValue }, {},{timeOut: 2}).success,
"execFail" : eval("main.dwl", {"main.dwl": "dw::Runtime::fail('My Bad')" }, {"payload": jsonValue }),
"parseFail" : eval("main.dwl", {"main.dwl": "(1 + " }, {"payload": jsonValue }),
"writerFail" : eval("main.dwl", {"main.dwl": "output application/xml --- 2" }, {"payload": jsonValue }),
"defaultOutput" : eval("main.dwl", {"main.dwl": "payload" }, {"payload": jsonValue2}, {},{outputMimeType: "application/csv", writerProperties: {"separator": "|"}}),
"onExceptionFail": do {
dw::Runtime::try( () ->
eval("main.dwl", {"main.dwl": "dw::Runtime::fail('Failing Test')" }, {"payload": jsonValue2}, {},{onException: "FAIL"})
).success
},
"customLogger":
eval(
"main.dwl",
{"main.dwl": "log(1234)" },
{"payload": jsonValue2},
{},
{
loggerService: {
initialize: () -> {token: "123"},
log: (level, msg, context) -> log("$(level) $(msg)", context)
}
}
)
}
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
116
117
118
119
120
121
{
"execute_ok": {
"success": true,
"value": "{\n a: 1\n}",
"mimeType": "application/dw",
"encoding": "UTF-8",
"logs": [
]
},
"logs": {
"m": [
"1"
],
"l": [
"INFO"
]
},
"grant": {
"success": false,
"message": "The given required permissions: `Resource` are not being granted for this execution.\nTrace:\n at readUrl (Unknown)\n at main::main (line: 1, column: 5)",
"location": {
"start": {
"index": 0,
"line": 0,
"column": 0
},
"end": {
"index": 0,
"line": 0,
"column": 0
},
"content": "Unknown location"
},
"stack": [
"readUrl (anonymous:0:0)",
"main (main:1:5)"
],
"logs": [
]
},
"library": {
"success": true,
"value": 3,
"logs": [
]
},
"timeout": true,
"execFail": {
"success": false,
"message": "My Bad\nTrace:\n at fail (Unknown)\n at main::main (line: 1, column: 1)",
"location": {
"start": {
"index": 0,
"line": 0,
"column": 0
},
"end": {
"index": 0,
"line": 0,
"column": 0
},
"content": "Unknown location"
},
"stack": [
"fail (anonymous:0:0)",
"main (main:1:1)"
],
"logs": [
]
},
"parseFail": {
"success": false,
"message": "Invalid input \"1 + \", expected parameter or parenEnd (line 1, column 2):\n\n\n1| (1 + \n ^^^^\nLocation:\nmain (line: 1, column:2)",
"location": {
"start": {
"index": 0,
"line": 1,
"column": 2
},
"end": {
"index": 4,
"line": 1,
"column": 6
},
"content": "\n1| (1 + \n ^^^^"
},
"logs": [
]
},
"writerFail": {
"success": true,
"value": 2,
"logs": [
]
},
"defaultOutput": {
"success": true,
"value": {
"name": "Mariano",
"lastName": "achaval"
},
"logs": [
]
},
"onExceptionFail": false,
"customLogger": {
"success": true,
"value": 1234,
"logs": [
]
}
}
3.1.3. evalUrl
evalUrl(String, Dictionary<ReaderInput>, Dictionary<Any>, RuntimeExecutionConfiguration): EvalSuccess | ExecutionFailure
EXPERIMENTAL
Evaluates the script under the specified url.
| Name | Description |
|---|---|
url |
The file name to execute |
readerInputs |
The inputs that are going to be read and bind to the execution |
inputValues |
The inputs that are going to be bind directly to the execution |
configuration |
The runtime configuration. |
Example
This example shows how the evalUrl behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
%dw 2.0
import * from dw::Runtime
var jsonValue = {
value: '{"name": "Mariano"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var Utils = "fun sum(a,b) = a +b"
output application/json
---
{
"execute_ok" : evalUrl("classpath://org/mule/weave/v2/engine/runtime_evalUrl/example.dwl", {"payload": jsonValue }),
"execute_ok_withValue" : evalUrl("classpath://org/mule/weave/v2/engine/runtime_evalUrl/example.dwl", {}, {"payload": {name: "Mariano"}})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"execute_ok": {
"success": true,
"value": "Mariano",
"logs": [
]
},
"execute_ok_withValue": {
"success": true,
"value": "Mariano",
"logs": [
]
}
}
3.1.4. 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.5. 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.6. 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.7. 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.8. 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.9. 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.10. 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.11. run
run(String, Dictionary<String>, Dictionary<ReaderInput>, Dictionary<Any>, RuntimeExecutionConfiguration): RunSuccess | ExecutionFailure
EXPERIMENTAL
Runs a given script under the provided context. This function will execute this given script in the current runtime.
Parameters
| Name | Description |
|---|---|
fileToExecute |
The file name to execute |
fs |
The file system where to look for the files |
readerInputs |
The inputs that are going to be read and bind to the execution |
inputValues |
The inputs that are going to be bind directly to the execution |
configuration |
The runtime configuration. |
Example
This example shows how the run behaves under different inputs.
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
import * from dw::Runtime
var jsonValue = {
value: '{"name": "Mariano"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var jsonValue2 = {
value: '{"name": "Mariano", "lastName": "achaval"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var invalidJsonValue = {
value: '{"name": "Mariano' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var Utils = "fun sum(a,b) = a +b"
---
{
"execute_ok" : run("main.dwl", {"main.dwl": "{a: 1}"}, {"payload": jsonValue }),
"logs" : do {
var execResult = run("main.dwl", {"main.dwl": "{a: log(1)}"}, {"payload": jsonValue })
---
{
m: execResult.logs.message,
l: execResult.logs.level
}
},
"grant" : run("main.dwl", {"main.dwl": "{a: readUrl(`http://google.com`)}"}, {"payload": jsonValue }, { securityManager: (grant, args) -> false }),
"library" : run("main.dwl", {"main.dwl": "Utils::sum(1,2)", "/Utils.dwl": Utils }, {"payload": jsonValue }),
"timeout" : run("main.dwl", {"main.dwl": "(1 to 1000000000000) map \$ + 1" }, {"payload": jsonValue }, {timeOut: 2}).success,
"execFail" : run("main.dwl", {"main.dwl": "dw::Runtime::fail('My Bad')" }, {"payload": jsonValue }),
"parseFail" : run("main.dwl", {"main.dwl": "(1 + " }, {"payload": jsonValue }),
"writerFail" : run("main.dwl", {"main.dwl": "output application/xml --- 2" }, {"payload": jsonValue }),
"readerFail" : run("main.dwl", {"main.dwl": "output application/xml --- payload" }, {"payload": invalidJsonValue }),
"defaultOutput" : run("main.dwl", {"main.dwl": "payload" }, {"payload": jsonValue2}, {outputMimeType: "application/csv", writerProperties: {"separator": "|"}}),
}
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
{
"execute_ok": {
"success": true,
"value": "{\n a: 1\n}",
"mimeType": "application/dw",
"encoding": "UTF-8",
"logs": [
]
},
"logs": {
"m": [
"1"
],
"l": [
"INFO"
]
},
"grant": {
"success": false,
"message": "The given required permissions: `Resource` are not being granted for this execution.\nTrace:\n at readUrl (Unknown)\n at main::main (line: 1, column: 5)",
"location": {
"start": {
"index": 0,
"line": 0,
"column": 0
},
"end": {
"index": 0,
"line": 0,
"column": 0
},
"content": "Unknown location"
},
"stack": [
"readUrl (anonymous:0:0)",
"main (main:1:5)"
],
"logs": [
]
},
"library": {
"success": true,
"value": "3",
"mimeType": "application/dw",
"encoding": "UTF-8",
"logs": [
]
},
"timeout": false,
"execFail": {
"success": false,
"message": "My Bad\nTrace:\n at fail (Unknown)\n at main::main (line: 1, column: 1)",
"location": {
"start": {
"index": 0,
"line": 0,
"column": 0
},
"end": {
"index": 0,
"line": 0,
"column": 0
},
"content": "Unknown location"
},
"stack": [
"fail (anonymous:0:0)",
"main (main:1:1)"
],
"logs": [
]
},
"parseFail": {
"success": false,
"message": "Invalid input \"1 + \", expected parameter or parenEnd (line 1, column 2):\n\n\n1| (1 + \n ^^^^\nLocation:\nmain (line: 1, column:2)",
"location": {
"start": {
"index": 0,
"line": 1,
"column": 2
},
"end": {
"index": 4,
"line": 1,
"column": 6
},
"content": "\n1| (1 + \n ^^^^"
},
"logs": [
]
},
"writerFail": {
"success": false,
"message": "Trying to output non-whitespace characters outside main element tree (in prolog or epilog), while writing Xml at .",
"location": {
"content": ""
},
"stack": [
],
"logs": [
]
},
"readerFail": {
"success": false,
"message": "Unexpected end-of-input at payload@[1:18] (line:column), expected '\"', while reading `payload` as Json.\n \n1| {\"name\": \"Mariano\n ^",
"location": {
"content": "\n1| {\"name\": \"Mariano\n ^"
},
"stack": [
],
"logs": [
]
},
"defaultOutput": {
"success": true,
"value": "name|lastName\nMariano|achaval\n",
"mimeType": "application/csv",
"encoding": "UTF-8",
"logs": [
]
}
}
3.1.12. runUrl
runUrl(String, Dictionary<ReaderInput>, Dictionary<Any>, RuntimeExecutionConfiguration): RunSuccess | ExecutionFailure
EXPERIMENTAL
Runs the script under the specified url.
| Name | Description |
|---|---|
url |
The file name to execute |
readerInputs |
The inputs that are going to be read and bind to the execution |
inputValues |
The inputs that are going to be bind directly to the execution |
configuration |
The runtime configuration. |
Example
This example shows how the runUrl behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
import * from dw::Runtime
var jsonValue = {
value: '{"name": "Mariano"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var Utils = "fun sum(a,b) = a +b"
---
{
"execute_ok" : runUrl("classpath://org/mule/weave/v2/engine/runtime_runUrl/example.dwl", {"payload": jsonValue })
}
1
2
3
4
5
6
7
8
9
10
11
{
"execute_ok": {
"success": true,
"value": "\"Mariano\"",
"mimeType": "application/dw",
"encoding": "UTF-8",
"logs": [
]
}
}
3.1.13. 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"
}
The orElseTry and orElse functions will also continue processing if the try function fails. See the orElseTry and orElse documentation for more complete examples of handling failing try function expressions.
Note: Instead of using the orElseTry and orElse functions, 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.14. 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 intended 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. DataFormatDescriptor
EXPERIMENTAL
Describes a DataFormat providing all the metadata information.
1
{ name: String, binary: Boolean, defaultEncoding?: String, extensions: Array<String>, defaultMimeType: String, acceptedMimeTypes: Array<String>, readerProperties: Array<DataFormatProperty>, writerProperties: Array<DataFormatProperty> }
3.2.2. DataFormatProperty
1
{ name: String, optional: Boolean, defaultValue?: Any, description: String, possibleValues: Array<Any> }
3.2.3. EvalSuccess
EXPERIMENTAL
When the eval function executes with no problem
1
{ success: true, value: Any, logs: Array<LogEntry> }
3.2.4. ExecutionFailure
EXPERIMENTAL
When the run or eval function failed.
1
{ success: false, message: String, stack?: Array<String>, location: Location, logs: Array<LogEntry> }
3.2.5. Location
1
{ start?: Position, end?: Position, content: String }
3.2.6. LogEntry
1
{ level: LogLevel, timestamp: String, message: String }
3.2.7. LogLevel
1
"INFO" | "ERROR" | "WARN"
3.2.8. LoggerService
EXPERIMENTAL
This service handles all the logging.
1
2
3
4
5
6
7
8
9
10
11
{ /**
* This function is going to be called when the execution starts.
* The result is going to be sent in every log so for example if some logging header needs to be sent it could be done at initialize and then recover in each log.
**/
initialize?: () -> Object, /**
* This log method is going to be called on every log message
**/
log: (level: LogLevel, msg: String, context: Object) -> Any, /**
* When the execution finished it is going to be called. Good time to flush any buffer or to gracefully logout.
**/
shutdown?: () -> Boolean }
3.2.9. MimeType
A MimeType represented in a String
1
String
3.2.10. Position
1
{ index: Number, line: Number, column: Number }
3.2.11. ReaderInput
EXPERIMENTAL
An Reader Input. This is input is going to be used as the source content of the reader created by the specified mimeType
1
2
3
4
5
6
7
8
9
10
11
12
13
{ /**
* The actual input
**/
value: Binary, /**
* The encoding to be used
**/
encoding?: String, /**
* The reader properties to be used to parse this input
**/
properties?: Dictionary<SimpleType>, /**
* The mimeType of this input.
**/
mimeType: MimeType }
3.2.12. RunSuccess
EXPERIMENTAL
When the run function executes with no problem
1
{ success: true, value: Binary, mimeType: MimeType, encoding?: String, logs: Array<LogEntry> }
3.2.13. RuntimeExecutionConfiguration
EXPERIMENTAL
Configures the runtime execution with some advance parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{ /**
* The max time this script should take.
**/
timeOut?: Number, /**
* The default output mimeType if it is not specified in the script
**/
outputMimeType?: MimeType, /**
* The writer properties to be used when the specified the *outputMimeType* property.
**/
writerProperties?: Dictionary<SimpleType>, /**
* When an the execution fails what it should happen. When *Handle* (default value) is specify the execution will return *ExecutionFailure* if *Fail* is specify
* then the *Exception* is going to be propagated.
**/
onException?: "HANDLE" | "FAIL", /**
* The *SecurityManager* to use in this execution. This security manager is going to be composed with the *current* SecurityManager.
**/
securityManager?: SecurityManager, /**
* The *LoggerService* to be used in this execution.
**/
loggerService?: LoggerService }
3.2.14. SecurityManager
EXPERIMENTAL
This function is going to be called every time some permissions needs to be granted to the current execution. The grant is the name of the Permission i.e: Resource The args represents the list of parameters the function that is requesting the permission is being called.
1
(grant: String, args: Array<Any>) -> Boolean
3.2.15. TryResult
Object with a result or error message. If success is false, it contains
the error. If true, it provides the result.
1
2
3
4
{ success: Boolean, result?: T, error?: { kind: String, message: String, stack?: Array<String>, /**
* Since 4.3.1. It is only available when stack is not present. It will contain the native java stacktrace.
**/
stackTrace?: 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 return true when the matching function is applied to the value of each element.
Parameters
| Name | Description |
|---|---|
|
The input array that contains elements to match. |
|
A function to apply to elements in the input array. |
Example
This example counts the number of elements in the input array ([1, 2, 3, 4]) that
return true when the function (($ mod 2) == 0) is applied their values. In this
case, the values of two of the elements, both 2 and 4, match because
2 mod 2 == 0 and 4 mod 2 == 0. As a consequence, the countBy function returns 2.
Note that mod returns the modulus of the operands.
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 than or equal to 2.
The last two elements (2 and 1) are included in the output array because the
function stops dropping elements when it reaches the 3, which 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,3,2,1]
---
arr dropWhile $ < 3
1
2
3
4
5
[
3,
2,
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 that enables every to 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 satisfies the condition, or returns null if no
element meets the condition.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
array |
The array of elements to search. |
condition |
The condition to satisfy. |
Example
This example shows how firstWith behaves when an element matches and when an element does not match.
1
2
3
4
5
6
7
8
9
%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. If the value is not found, it returns -1.
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 parameter 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 that enables some to 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
with an index that is <= 1 and stops selecting elements when it reaches
one that is greater than 2. Notice that it does not select the second 1 because
of the 2 that precedes it 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,1]
---
arr takeWhile $ <= 1
1
2
3
4
[
0,
1
]
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".
To show you the type, it outputs data in the application/dw format.
1
2
3
4
5
%dw 2.0
import * from dw::core::Binaries
output application/dw
---
{ "hexToBinary": fromHex("4D756C65") }
1
2
3
{
hexToBinary: "TXVsZQ==" as Binary {base: "64"}
}
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 that enables fromBinary to 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 that enables fromHex to 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 that enables toBinary to 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 that enables toHex to 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 is Deprecated. Use entriesOf from Core module, instead.
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 object.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
|
The object to evaluate. |
|
The condition to apply to each element. |
Example
This example shows how everyEntry behaves with 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 enables everyEntry to work with a null value.
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 is Deprecated. Use keysOf from Core module, instead.
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 function that enables mergeWith to work with a null value.
mergeWith(T, Null): T
Helper function that enables mergeWith to work with a null value.
8.1.6. nameSet
nameSet(Object): Array<String>
Returns an array of keys from an object.
This method is Deprecated. Use namesOf from Core module, instead.
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 |
|---|---|
|
The object to evaluate. |
|
The condition to use when evaluating elements in the object. |
Example
This example shows how the someEntry behaves with 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 enables someEntry to work with a null value.
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 filter. |
|
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 is Deprecated. Use valuesOf from Core module, instead.
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 consisting of the number of years, months,
and days between two dates.
The start date is included, but the end date is not.
The period is calculated by removing complete months, then calculating
the remaining number of days, adjusting to ensure that both have the same sign.
The number of months is then split into years and months based on a 12 month year.
A month is considered if the end day-of-month is greater than or equal to the start day-of-month.
For example, from 2010-01-15 to 2011-03-18 is one year, two months and three days.
The result of this method can be a negative period if the end is before the start.
_Introduced in DataWeave 2.3.1. Supported by Mule 4.3.1 and later._
Parameters
| Name | Description |
|---|---|
startDateInclusive |
the start date, inclusive. |
endDateExclusive |
the end date, exclusive. |
Example
This example shows how the between behaves under different inputs.
1
2
3
4
5
6
7
import * from dw::core::Periods
output application/json
---
{
a: between(|2010-12-12|,|2010-12-10|),
b: between(|2010-12-10|,|2011-12-11|)
}
1
2
3
4
{
"a": "P2D",
"b": "P-1Y-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 that enables appendIfMissing to work with a 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 enables camelize to work with a null value.
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 enables capitalize to work with a null value.
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 enables dasherize to work with a null value.
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 that enables isAlpha to work with a 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 that enables isAlphanumeric to work with a 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 that enables isLowerCase to work with a 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 that enables isNumeric to work with a 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 that enables isUpperCase to work with a 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 that enables isWhitespace to work with a 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 that enables leftPad to work with a 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 enables ordinalize to work with a null value.
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 enables pluralize to work with a null value.
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 that enables prependIfMissing to work with a 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 that enables rightPad to work with a 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 enables singularize to work with a null value.
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 that enables substringAfter to work with a 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 that enables substringAfterLast to work with a 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 that enables substringBefore to work with a 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": "ab"
}
substringBeforeLast(Null, String): Null
Helper function that enables substringBeforeLast to work with a 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 enables underscore to work with a null value.
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 that enables unwrap to work with a null value.
10.1.27. withMaxSize
withMaxSize(String, Number): String
Checks that the string length is no larger than the specified maxLength.
If the string’s length is larger than the maxLength, the function cuts
characters from left to right, until the string length meets the length limit.
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.
Note that if withMaxSize is 0, the function returns an empty string. If
the input is null, the output is always null.
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 that enables withMaxSize to work with a 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 that enables wrapIfMissing to work with a 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 that enables wrapWith to work with a null value.
11. dw::core::Types
This module enables you to perform type introspection.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Types to the header of your
DataWeave script.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
11.1. Functions
11.1.1. arrayItem
arrayItem(Type): Type
Returns the type of the given array. This function fails if the input 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 check. |
Example
This example shows how arrayItem behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import * from dw::core::Types
type ArrayOfString = Array<String>
type ArrayOfNumber = Array<Number>
type ArrayOfAny = Array<Any>
type ArrayOfAnyDefault = Array
output application/json
---
{
a: arrayItem(ArrayOfString),
b: arrayItem(ArrayOfNumber),
c: arrayItem(ArrayOfAny),
d: arrayItem(ArrayOfAnyDefault)
}
1
2
3
4
5
6
{
"a": "String",
"b": "Number",
"c": "Any",
"d": "Any"
}
11.1.2. baseTypeOf
baseTypeOf(Type): Type
Returns an the base type of the given type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how baseTypeOf behaves with different inputs.
1
2
3
4
5
6
7
8
%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 from the given function type. This function fails if the provided type is not a Function type.
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 functionParamTypes behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 a function’s return type. This function fails if the input type is not a Function type.
_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 functionReturnType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 that define a given Intersection type. This function fails if the input 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 check. |
Example
This example shows how intersectionItems behaves with different inputs.
Note that the AType variable defines an Intersection type
{name: String} & {age: Number} by using an & between
the two objects.
1
2
3
4
5
6
7
8
%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 the input is the Any type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isAnyType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 input type is the Array type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isArrayType behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AType = Array<String>
output application/json
---
{
a: isArrayType(AType),
b: isArrayType(Boolean),
}
1
2
3
4
{
"a": true,
"b": false
}
11.1.8. isBinaryType
isBinaryType(Type): Boolean
Returns true if the input is the Binary type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isBinaryType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Boolean type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isBooleanType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the DateTime type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isDateTimeType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Date type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isDateType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Function type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isFunctionType behaves with different inputs.
1
2
3
4
5
6
7
8
9
%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 input type is the Intersection type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isIntersectionType behaves with 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: isIntersectionType(AType),
b: isIntersectionType(Boolean),
}
1
2
3
4
{
"a": true,
"b": false
}
11.1.14. isKeyType
isKeyType(Type): Boolean
Returns true if the input is the Key type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isKeyType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Literal type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isLiteralType behaves with different inputs.
1
2
3
4
5
6
7
8
9
%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 the input is the LocalDateTime type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isLocalDateTimeType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the LocalTime type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isLocalTimeType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Namespace type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isNamespaceType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Nothing type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isNothingType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Null type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isNullType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Number type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isNumberType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 input is the Object type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isObjectType behaves with different inputs.
1
2
3
4
5
6
7
8
9
%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 the input is the Period type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isPeriodType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Range type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isRangeType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ARange = Range
output application/json
---
{
a: isRangeType(ARange),
b: isRangeType(Range),
c: isRangeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
11.1.25. isReferenceType
isReferenceType(Type): Boolean
Returns true if the input type is a Reference type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isReferenceType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%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 the input is the Regex type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isRegexType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the String type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isStringType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Time type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isTimeType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the TimeZone type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isTimeZoneType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 the input is the Type type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isTypeType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 input type is the Union type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isUnionType behaves with different inputs.
1
2
3
4
5
6
7
8
9
%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 the input is the Uri type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how isUriType behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%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 an input belongs to the Literal type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how literalValueOf behaves with different inputs.
1
2
3
4
5
6
7
8
%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 metadata that is 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 check. |
Example
This example shows how metadataOf behaves with different inputs.
1
2
3
4
5
6
7
8
%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 the input 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 nameOf behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%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 from the given Object type. This function fails if the type is not an Object type.
_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 objectFields behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
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
{
"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"
}
]
}
11.1.37. unionItems
unionItems(Type): Array<Type>
Returns an array of all the types that define a given Union type. This function fails if the input is not a Union type.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Parameters
| Name | Description |
|---|---|
t |
The type to check. |
Example
This example shows how unionItems behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::core::Types
type AType = String | Number
output application/json
---
{
a: unionItems(AType)
}
1
2
3
{
"a": ["String","Number"]
}
11.2. Types
11.2.1. Attribute
Represents an Attribute definition that is part of an Object field Key.
1
{ name: QName, required: Boolean, value: Type }
11.2.2. Field
Represents a Field description that is part of an Object.
1
{ key: { name: QName, attributes: Array<Attribute> }, required: Boolean, repeated: Boolean, value: Type }
11.2.3. FunctionParam
Represents a Function parameter that is part of a Function type.
1
{ paramType: Type, optional: Boolean }
11.2.4. QName
Represents a Qualified Name definition with a localName (a string) and a namespace.
If the QName does not have a Namespace, its value is null.
1
{ localName: String, namespace: Namespace | Null }
12. 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.
12.1. Functions
12.1.1. compose
compose(Array<String>, Array<String>): String
Uses a custom string interpolator to replace URL components with a
encodeURIComponent result. You can call this function using the standard call, or a simplified version.
Parameters
| Name | Description |
|---|---|
|
A string array that contains the URL parts to interpolate using the strings in the |
|
A string array that contains the strings used to interpolate the |
Example
The following example uses the compose function to form an encoded URL, the first parameter is an array of two strings that are part of the URL
and the second parameter is the urlPath variable that is used to interpolate the strings in the first parameter.
Notice that the spaces in the input are encoded in the output URL as %20.
1
2
3
4
5
6
%dw 2.0
output application/json
var urlPath = "content folder"
import * from dw::core::URL
---
{ "encodedURL" : compose(["http://examplewebsite.com/", "/page.html"], ["$(urlPath)"]) }
1
{ "encodedURL" : "http://examplewebsite.com/content%20folder/page.html" }
12.2. Simplified Syntax
You can also call this function using the simplified syntax, which uses backticks (`) to enclose the string that includes the variable
to encode.
Example
This example shows how to use the simplified syntax to obtain the same result as in the previous example.
1
2
3
4
5
6
%dw 2.0
output application/json
var urlPath = "content folder"
import * from dw::core::URL
---
{ "encodedURL" : compose `http://examplewebsite.com/$(urlPath)/page.html`}
1
{ "encodedURL" : "http://examplewebsite.com/content%20folder/page.html" }
12.2.2. 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
| Name | Description |
|---|---|
|
The URI to decode. |
Example
This example decodes a URI that contains the URL percent encoding %20,
which is used for spaces.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::URL
output application/json
---
{
"decodeURI" : decodeURI('http://asd/%20text%20to%20decode%20/text')
}
1
2
3
{
"decodeURI": "http://asd/ text to decode /text"
}
12.2.3. 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
| Name | Description |
|---|---|
|
URI component string. |
Example
This example decodes a variety of URI components.
1
2
3
4
5
6
7
8
9
10
11
%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"),
}
}
1
2
3
4
5
6
7
{
decodeURIComponent: {
decodeURIComponent: " PATH/ TO /DECODE ",
decodeURIComponent: ";,/?:@&=",
decodeURIComponent: "-_.!~*'()\$"
}
}
12.2.4. 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:
| Type (not escaped) | Examples |
|---|---|
Reserved characters |
; , / ? : @ & = $ |
Unescaped characters |
alphabetic, decimal digits, - _ . ! ~ * ' ( ) |
Number sign |
# |
Parameters
| Name | Description |
|---|---|
|
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.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::core::URL
output application/json
---
{
"encodeURI" : encodeURI("http://asd/ text to decode /text"),
"not_encoded": encodeURI("http://:;,/?:@&=\$_-_.!~*'()")
}
1
2
3
4
{
"encodeURI": "http://asd/%20text%20to%20decode%20/%25/\"\'/text",
"not_encoded": "http://:;,/?:@&=$_-_.!~*'()"
}
12.2.5. 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:
| Type | Includes |
|---|---|
Reserved characters |
|
Unescaped characters |
alphabetic, decimal digits, - _ . ! ~ * ' ( ) |
Number sign |
Parameters
| Name | Description |
|---|---|
|
URI component string. |
Example
This example encodes a variety of URI components.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%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("-_.!~*'()")
}
}
1
2
3
4
5
6
7
8
9
10
{
"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": "-_.!~*'()"
}
}
12.2.6. 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
| Name | Description |
|---|---|
|
The URI input. |
Example
This example parses a URL.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::URL
output application/json
---
{
'composition': parseURI('https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#footer')
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"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
}
}
12.3. Types
12.3.1. URI
Describes the URI type. For descriptions of the fields, see URL Types (dw::core::URL).
1
{ isValid: Boolean, host?: String, authority?: String, fragment?: String, path?: String, port?: Number, query?: String, scheme?: String, user?: String, isAbsolute?: Boolean, isOpaque?: Boolean }
13. dw::extension::DataFormat
This module contains what is required for registering a new data format for the DataWeave language.
For an example, see Custom Data Formats Example.
13.1. Types
13.1.1. DataFormat
Represents the DataFormat definition.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{ /**
* 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 }
13.1.2. EmptySettings
Represents a configuration with no Settings.
1
Object
13.1.3. EncodingSettings
Represents an Encoding Settings.
1
2
3
4
{ /**
* Encoding to be used by this writer.
**/
encoding?: String {defaultValue: "UTF-8"} }
13.1.4. MimeType
Represents a MimeType, such as application/json.
1
String
13.1.5. Settings
Represents reader or writer configuration Settings.
1
Object
13.2. Annotations
14. 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.
14.1. Functions
14.1.1. 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
| Name | Description |
|---|---|
|
Array of objects that specifies:
|
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.
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
%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"})
}
}
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
------=_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:
1
Multipart::field("order", myOrder,"application/json", "order.json")`
Parameters
| Name | Description |
|---|---|
|
A set of parameters that specify:
|
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.
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
%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")
}
}
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
------=_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--
14.1.2. 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:
1
Multipart::file({ name: "myFile", path: "myClients.json", mime: "application/json", fileName: "partMyClients.json"})
Parameters
| Name | Description |
|---|---|
|
Array of objects that specifies:
|
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.
1
2
3
4
5
6
7
8
9
%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)
])
A file called myClients.json and located in src/main/resources with the
following content.
1
2
3
4
5
6
7
8
9
10
clients: {
client: {
id: 1,
name: "Mariano"
},
client: {
id: 2,
name: "Shoki"
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
------=_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:
1
Multipart::field("myFile", myClients, 'application/json', "partMyClients.json")
Parameters
| Name | Description |
|---|---|
|
Array of objects that specifies:
|
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.
1
2
3
4
5
6
7
8
%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")
])
A file called myClients.json and located in src/main/resources with the
following content.
1
2
3
4
5
6
7
8
9
10
clients: {
client: {
id: 1,
name: "Mariano"
},
client: {
id: 2,
name: "Shoki"
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
------=_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--
14.1.3. form
form(Array<MultipartPart>): Multipart
Creates a Multipart data structure using a specified array of parts.
Parameters
| Name | Description |
|---|---|
|
An array of parts ( |
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
documentation.
1
2
3
4
5
6
7
8
9
10
11
12
%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)
}
}
1
2
3
4
5
6
7
8
9
------=_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--
14.1.4. generateBoundary
generateBoundary(Number): String
Helper function for generating boundaries in Multipart data structures.
14.2. Types
14.2.1. Multipart
MultiPart type, a data structure for a complete Multipart format. See the
output example for the Multipart form function
documentation.
1
{ preamble?: String, parts: { _?: MultipartPart } }
14.2.2. MultipartPart
MultipartPart type, a data structure for a part within a MultiPart format.
See the output examples for the Multipart field function
documentation.
1
{ headers?: { "Content-Disposition"?: { name: String, filename?: String }, "Content-Type"?: String }, content: Any }
15. 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.
15.1. Functions
15.1.1. 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
| Name | Description |
|---|---|
|
The actual value. Can be any data type. |
|
The expected value to compare to the actual. Can be any data type. |
|
Setting for changing the default to unordered using `{ "unordered" : true} (explained in the introduction). |
Example
This example shows a variety of uses of diff.
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
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"}]
}
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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: []
}
}
15.2. Types
15.2.1. 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.
1
{ matches: Boolean, diffs: Array<Difference> }
15.2.2. Difference
Describes a single difference between two values at a given structure.
1
{ expected: String, actual: String, path: String }
16. 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.
16.1. Functions
16.1.1. currentMilliseconds
currentMilliseconds(): Number
Returns the current time in milliseconds.
Example
This example shows the time in milliseconds when the function executed.
1
2
3
4
5
%dw 2.0
import * from dw::util::Timer
output application/json
---
{ "currentMilliseconds" : currentMilliseconds() }
1
{ "currentMilliseconds": 1532923168900 }
16.1.2. duration
duration(() → T): DurationMeasurement<T>
Executes the input function and returns an object with execution time in milliseconds and result of that function.
Parameters
| Name | Description |
|---|---|
|
A function to pass to |
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.
1
2
3
4
5
%dw 2.0
output application/json
fun myFunction() = dw::Runtime::wait("My result",100)
---
dw::util::Timer::duration(() -> myFunction())
1
2
3
4
{
"time": 101,
"result": "My result"
}
16.1.3. 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
| Name | Description |
|---|---|
|
A function to pass to |
Example
This example passes wait and sum functions (defined in the
header), which return their results in TimeMeasurement
objects.
1
2
3
4
5
6
7
8
9
10
%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())
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"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"
}
]
}
16.1.4. toMilliseconds
toMilliseconds(DateTime): Number
Returns the representation of a specified date-time in milliseconds.
Parameters
| Name | Description |
|---|---|
|
A |
Example
This example shows a date-time in milliseconds.
1
2
3
4
5
%dw 2.0
import * from dw::util::Timer
output application/json
---
{ "toMilliseconds" : toMilliseconds(|2018-07-23T22:03:04.829Z|) }
1
{ "toMilliseconds": 1532383384829 }
16.2. Types
16.2.1. DurationMeasurement
A return type that contains the execution time and result of a function call.
1
{ time: Number, result: T }
16.2.2. TimeMeasurement
A return type that contains a start time, end time, and result of a function call.
1
{ start: DateTime, result: T, end: DateTime }
17. 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.
17.1. Functions
17.1.1. asExpressionString
asExpressionString(Path): String
Transforms a path to a string representation.
Parameters
| Name | Description |
|---|---|
path |
The path to transform to a string. |
Example
This example transforms a path to a string representation.
1
2
3
4
5
%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}])
1
".user.@name"
17.1.2. filterArrayLeafs
filterArrayLeafs(Any, (value: Any, path: Path) → Boolean): Any
This function filter only the Array Leaf values.
So the criteria is only going to be applied to Arrays values which values are
either SimpleType or Null
Introduced in DataWeave 2.3.1. Supported by Mule 4.3.1 and later.
Parameters
| Name | Description |
|---|---|
value |
The value to be filtered |
criteria |
The criteria to be used to filter the arrays |
Example
This example shows how the filterArrayLeafs behaves under different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Tree
output application/json
---
{
a: [1,2, {name: ["", true], test: 213}, "123"] filterArrayLeafs ((value, path) -> !(value is Null or value is String)),
b: null filterArrayLeafs ((value, path) -> !(value is Null or value is String))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
a: [
1,
2,
{
name: [
true
],
test: 213
}
],
b: null
}
17.1.3. filterObjectLeafs
filterObjectLeafs(Any, (value: Any, path: Path) → Boolean): Any
This function filter only the Object Leaf values.
So the criteria is only going to be applied to Object values and Attributes which values are
either SimpleType or Null
Introduced in DataWeave 2.3.1. Supported by Mule 4.3.1 and later.
Parameters
| Name | Description |
|---|---|
value |
The value to be used |
criteria |
The criteria to be used to filter the Object values. |
Example
This example shows how the filterObjectLeafs behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
%dw 2.0
import * from dw::util::Tree
output application/json
---
---
{
a: {
name: "Mariano",
lastName: null,
age: 123,
friends: [{name @(mail: "mariano.achaval@gmail.com", test:123 ): "", id:"test"}, {name: "Mariano", id:null}]
} filterObjectLeafs ((value, path) -> !(value is Null or value is String)),
b: null filterObjectLeafs ((value, path) -> !(value is Null or value is String))
}
1
2
3
4
5
6
7
8
9
10
{
a: {
age: 123,
friends: [
{},
{}
]
},
b: null
}
17.1.4. filterTree
filterTree(Any, (value: Any, path: Path) → Boolean): Any
Go through the nodes of the value and allows to filter them.
The criteria is going to be called with each value and its path.
If it returns true the node will remain if false it will be filtered.
Introduced in DataWeave 2.3.1. Supported by Mule 4.3.1 and later. ===== Parameters
| Name | Description |
|---|---|
value |
The value to be filtered |
criteria |
The expression that will determine if the node is filtered or not. |
Example
This example shows how the filterTree behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
%dw 2.0
import * from dw::util::Tree
output application/json
---
{
a: {name : "", lastName @(foo: ""): "Achaval", friends @(id: 123): [{id: "", test: true}, {age: 123}, ""]} filterTree ((value, path) ->
value match {
case s is String -> !isEmpty(s)
else -> true
}
),
b: null filterTree ((value, path) -> value is String),
c: [{name: "Mariano", friends: []}, {test: [1,2,3]}, {dw: ""}] filterTree ((value, path) -> value match {
case a is Array -> !isEmpty(a as Array)
else -> true
}),
}
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
{
a: {
lastName: "Achaval",
friends @(id: 123): [
{
test: true
},
{
age: 123
}
]
},
b: null,
c: [
{
name: "Mariano"
},
{
test: [
1,
2,
3
]
},
{
dw: ""
}
]
}
17.1.5. isArrayType
isArrayType(Path): Boolean
Returns true if the provided path is an Array Type expression
Introduced in DataWeave 2.3.1. Supported by Mule 4.3.1 and later.
Parameters
| Name | Description |
|---|---|
path |
The path to be validated |
Example
This example shows how the isAttributeType behaves under different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::utils::Tree
output application/json
---
{
a: isArrayType([{kind: OBJECT_TYPE, selector: "user", namespace: null}, {kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}]),
b: isArrayType([{kind: OBJECT_TYPE, selector: "user", namespace: null}, {kind: ARRAY_TYPE, selector: 0, namespace: null}])
}
1
2
3
4
{
a: false,
b: true
}
17.1.6. isAttributeType
isAttributeType(Path): Boolean
Returns true if the provided path is an Object Type expression
Introduced in DataWeave 2.3.1. Supported by Mule 4.3.1 and later.
Parameters
| Name | Description |
|---|---|
path |
The path to be validated |
Example
This example shows how the isAttributeType behaves under different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Tree
output application/json
---
{
a: isAttributeType([{kind: OBJECT_TYPE, selector: "user", namespace: null}, {kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}]),
b: isAttributeType([{kind: OBJECT_TYPE, selector: "user", namespace: null}, {kind: OBJECT_TYPE, selector: "name", namespace: null}])
}
1
2
3
4
{
a: true,
b: false
}
17.1.7. isObjectType
isObjectType(Path): Boolean
Returns true if the provided path is an Object Type expression
Introduced in DataWeave 2.3.1. Supported by Mule 4.3.1 and later.
Parameters
| Name | Description |
|---|---|
path |
The path to be validated |
Example
This example shows how the isAttributeType behaves under different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::utils::Tree
output application/json
---
{
a: isObjectType([{kind: OBJECT_TYPE, selector: "user", namespace: null}, {kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}]),
b: isObjectType([{kind: OBJECT_TYPE, selector: "user", namespace: null}, {kind: OBJECT_TYPE, selector: "name", namespace: null}])
}
1
2
3
4
{
a: false,
b: true
}
17.1.8. 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
| Name | Description |
|---|---|
|
The value to map. |
|
The mapper function. |
Example
This example transforms all the string values to upper case.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::util::Tree
output application/json
---
{
user: [{
name: "mariano",
lastName: "achaval"
}],
group: "data-weave"
} mapLeafValues (value, path) -> upper(value)
1
2
3
4
5
6
7
8
9
{
"user": [
{
"name": "MARIANO",
"lastName": "ACHAVAL"
}
],
"group": "DATA-WEAVE"
}
17.1.9. nodeExists
nodeExists(Any, (value: Any, path: Path) → Boolean): Boolean
Returns true if any node in the tree validates against the specified criteria.
Parameters
| Name | Description |
|---|---|
|
The value to search. |
|
The criteria. |
Example
This example checks for any user with the name peter.
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
%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")
1
true
17.2. Variables
17.2.1. ARRAY_TYPE
17.2.2. ATTRIBUTE_TYPE
17.2.3. OBJECT_TYPE
17.3. Types
17.3.1. Path
Represents an array of PathElement types that identify the location of a node in a tree.
1
Array<PathElement>
17.3.2. PathElement
Represents a specific selection of a node in a path.
1
{| kind: "Object" | "Attribute" | "Array", selector: String | Number, namespace: Namespace | Null |}
18. 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.
18.1. Functions
18.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"
}
18.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"
}
18.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
}
18.1.4. mask
mask(Null, String | Number | PathElement): (newValueProvider: (oldValue: Any, path: Path) → Any) → Null
Helper function that enables mask to work with a null value.
mask(Any, PathElement): (newValueProvider: (oldValue: Any, path: Path) → Any) → 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): (newValueProvider: (oldValue: Any, path: Path) → Any) → 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): (newValueProvider: (oldValue: Any, path: Path) → Any) → 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
]
]
18.1.5. update
update(Object, String): UpdaterValueProvider<Object>
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): UpdaterValueProvider<Object>
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): UpdaterValueProvider<Array>
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): UpdaterValueProvider<Array>
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): UpdaterValueProvider<Array>
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>): UpdaterValueProvider<Array | Object | Null>
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): UpdaterValueProvider<Null>
Helper function that enables update to work with a null value.
18.2. Types
18.2.1. UpdaterValueProvider
Type that represents the output type of the update function.
1
(newValueProvider: (oldValue: Any, index: Number) -> Any) -> ReturnType