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" }
++(Object, Object): Object
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
.
Example
This example concatenates LocalTime
and Date
objects to return a
LocalDateTime
.
Parameters
Name | Description |
---|---|
|
A |
|
A |
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.
A 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 for the values:
[0, 1, 2, 3, 3, 2, 1, 4] distinctBy $
1
2
3
4
%dw 2.0
output application/json
---
[0, 1, 2, 3, 3, 2, 1, 4] distinctBy (value) -> { "unique" : value }
1
[ 0, 1, 2, 3, 4]
Example
This example removes duplicates of "Kurt Cagle"
from an array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
%dw 2.0
output application/json
var record = {
"title": "XQuery Kick Start",
"author": [
"James McGovern",
"Per Bothner",
"Kurt Cagle",
"James Linn",
"Kurt Cagle",
"Kurt Cagle",
"Kurt Cagle",
"Vaidyanathan Nagarajan"
],
"year":"2000"
}
---
{
"book" : {
"title" : record.title,
"year" : record.year,
"authors" : record.author distinctBy $
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"book": {
"title": "XQuery Kick Start",
"year": "2000",
"authors": [
"James McGovern",
"Per Bothner",
"Kurt Cagle",
"James Linn",
"Vaidyanathan Nagarajan"
]
}
}
distinctBy(Null, (item: Nothing, index: Nothing) → Any): Null
Helper function that allows distinctBy to work with null values.
distinctBy({ (K)?: V }, (value: V, key: K) → Any): Object
Removes duplicate key-value pairs from an object.
Parameters
Name | Description |
---|---|
|
The object from which to remove the key-value pairs. |
|
The |
Example
This example inputs an object that contains duplicate key-value pairs and
returns an object with key-value pairs from that input. Notice that the
keys (a
and A
) are not treated with case sensitivity, but the values
(b
and B
) are. Also note that you can write the same expression using
an anonymous 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. filter
filter(Array<T>, (item: T, index: Number) → Boolean): Array<T>
Iterates over an array and applies an expression that returns matching values.
The expression must return true
or false
. If the expression returns true
for a value or index in the array, the value gets captured in the output array.
If it returns false
for a value or index in the array, that item gets
filtered out of the output. If there are no matches, the output array will
be empty.
Parameters
Name | Description |
---|---|
|
The array to filter. |
|
Boolean expression that selects an |
Example
This example returns an array of values in the array that are greater than 2
.
1
[9,2,3,4,5] filter (value, index) -> (value > 2)
1
[9,3,4,5]
Example
This example returns an array of all values found at an index greater than 2
.
1
[9,2,3,4,5] filter ((value, index) -> (index > 2))
1
[4,5]
Example
This example returns an array of all items found at an index ($$
)
greater than 1
where the value of the element is less than 5
. Notice that
it is using anonymous parameters as selectors instead of using named
parameters in an anonymous function.
1
2
3
4
%dw 2.0
output application/json
---
[9, 2, 3, 4, 5] filter (($$ > 1) and ($ < 5))
1
[3,4]
filter(Null, (item: Nothing, index: Nothing) → Boolean): Null
Helper function that allows filter
to work with null values.
1.1.11. filterObject
filterObject({ (K)?: V }, (value: V, key: K, index: Number) → Boolean): { (K)?: V }
Iterates a list of key-value pairs in an object and applies an expression that returns only matching objects, filtering out the rest from the output.
The expression must return true
or false
. If the expression returns true
for a key, value, or index of an object, the object gets captured in the
output. If it returns false
for any of them, the object gets filtered out
of the output. If there are no matches, the output array will be empty.
Parameters
Name | Description |
---|---|
|
The source object to evaluate. |
|
Boolean expression that selects a |
Example
This example outputs an object if its value equals "apple"
.
1
2
3
4
%dw 2.0
output application/json
---
{"a" : "apple", "b" : "banana"} filterObject ((value) -> value == "apple")
1
{ "a": "apple" }
Example
This example only outputs an object if the key starts with "letter". The
DataWeave startsWith
function returns true
or false
. Note that you can
use the anonymous parameter for the key to write the expression
((value, key) → key startsWith "letter")
: ($$ startsWith "letter")`
1
2
3
4
%dw 2.0
output application/json
---
{"letter1": "a", "letter2": "b", "id": 1} filterObject ((value, key) -> key startsWith "letter")
1
{ "letter1": "a", "letter2": "b" }
Example
This example only outputs an object if the index of the object in the array
is less than 1, which is always true of the first object. Note that you can
use the anonymous parameter for the index to write the expression
((value, key, index) → index < 1)
: ($$$ < 1)
1
2
3
4
%dw 2.0
output application/json
---
{ "1": "a", "2": "b", "3": "c"} filterObject ((value, key, index) -> index < 1)
1
{ "1": "a" }
filterObject(Null, (value: Nothing, key: Nothing, index: Nothing) → Boolean): Null
Helper function that allows filterObject
to work with null values.
1.1.12. 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.13. flatMap
flatMap(Array<T>, (item: T, index: Number) → Array<R>): Array<R>
Iterates over each item in an array and flattens the results.
Instead of returning an array of arrays (as map
does when you iterate over
the values within an input like [ [1,2], [3,4] ]
), flatMap
returns a
flattened array that looks like this: [1, 2, 3, 4]
. flatMap
is similar to
flatten
, but flatten
only acts on the values of the arrays, while
flatMap
can act on values and indices of items in the array.
Parameters
Name | Description |
---|---|
|
The array to map. |
|
Expression or selector for an |
Example
This example returns an array containing each value in order. Though it names
the optional index
parameter in its anonymous function
(value, index) → value
, it does not use index
as a selector for the
output, so it is possible to write the anonymous function using
(value) → value
. You can also use an anonymous parameter for the
value to write the example like this: [ [3,5], [0.9,5.5] ] flatMap $
.
Note that this example produces the same result as
flatten([ [3,5], [0.9,5.5] ])
, which uses flatten
.
1
2
3
4
%dw 2.0
output application/json
---
[ [3,5], [0.9,5.5] ] flatMap (value, index) -> value
1
[ 3, 5, 0.9, 5.5]
flatMap(Null, (item: Nothing, index: Nothing) → Any): Null
Helper function that allows flatMap
to work with null values.
1.1.14. flatten
flatten(Array<Array<T> | Q>): Array<T | Q>
Flattens an array of arrays into a single, simple array.
Parameters
Name | Description |
---|---|
|
The input array of arrays. |
Example
This example flattens an array of arrays.
1
2
3
4
%dw 2.0
output application/json
---
flatten([ [0.0, 0], [1,1], [2,3], [5,8] ])
1
[ 0.0, 0 1, 1, 2, 3, 5, 8 ]
flatten(Null): Null
Helper function that allows flatten to work with null values.
1.1.15. 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.16. groupBy
groupBy(Array<T>, (item: T, index: Number) → R): { ®: Array<T> }
Returns an object that groups items from an array based on specified criteria, such as an expression or matching selector.
This version of groupBy
groups the elements of an array using the
criteria
function. Other versions act on objects and handle null values.
Parameters
Name | Description |
---|---|
|
The array to group. |
|
Expression providing the criteria by which to group the items in the array. |
Example
This example groups items from the input array ["a","b","c"]
by their
indices. Notice that it returns the numeric indices as strings and that items
(or values) of the array are returned as arrays, in this case, with a single
item each. The items in the array are grouped based on an anonymous function
(item, index) → index
that uses named parameters (item
and index
).
Note that you can produce the same result using the anonymous parameter
$$
to identify the indices of the array like this:
["a","b","c"] groupBy $$
1
2
3
4
%dw 2.0
output application/json
---
["a","b","c"] groupBy (item, index) -> index
1
{ "2": [ "c" ], "1": [ "b" ], "0": [ "a" ] }
Example
This example groups the elements of an array based on the language field.
Notice that it uses the item.language
selector to specify the grouping
criteria. So the resulting object uses the "language" values ("Scala"
and
"Java"
) from the input to group the output. Also notice that the output
places the each input object in an array.
1
2
3
4
5
6
7
8
9
%dw 2.0
var myArray = [
{ "name": "Foo", "language": "Java" },
{ "name": "Bar", "language": "Scala" },
{ "name": "FooBar", "language": "Java" }
]
output application/json
---
myArray groupBy (item) -> item.language
1
2
3
4
5
6
7
8
9
{
"Scala": [
{ "name": "Bar", "language": "Scala" }
],
"Java": [
{ "name": "Foo", "language": "Java" },
{ "name": "FooBar", "language": "Java" }
]
}
Example
This example uses groupBy "myLabels"`to return an object where `"mylabels"
is the key, and an array of selected values
(["Open New", "Zoom In", "Zoom Out", "Original View" ]
) is the value. It
uses the selectors (myVar.menu.items.*label
) to create that array. Notice
that the selectors retain all values where "label"
is the key but filter
out values where "id"
is the key.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
var myVar = { menu: {
header: "Move Items",
items: [
{"id": "internal"},
{"id": "left", "label": "Move Left"},
{"id": "right", "label": "Move Right"},
{"id": "up", "label": "Move Up"},
{"id": "down", "label": "Move Down"}
]
}}
output application/json
---
(myVar.menu.items.*label groupBy "myLabels")
1
{ "myLabels": [ "Move Left", "Move Right", "Move Up", "Move Down" ] }
groupBy({ (K)?: V }, (value: V, key: K) → R): { ®: { (K)?: V } }
Groups elements of an object based on criteria that the groupBy
uses to iterate over elements in the input.
Parameters
Name | Description |
---|---|
|
The object containing objects to group. |
|
The grouping criteria to apply to elements in the input object, such as a |
Example
This example groups objects within an array of objects using the anonymous
parameter $
for the value of each key in the input objects. It applies
the DataWeave upper
function to those values. In the output, these values
become upper-case keys. Note that you can also write the same example using
a named parameter for the within an anonymous function like this:
{ "a" : "b", "c" : "d"} groupBy (value) → upper(value)
1
2
3
4
%dw 2.0
output application/json
---
{ "a" : "b", "c" : "d"} groupBy upper($)
1
{ "D": { "c": "d" }, "B": { "a": "b" } }
Example
This example uses groupBy "costs"
to produce a JSON object from an XML object
where "costs"
is the key, and the selected values of the XML element prices
becomes the JSON value ({ "price": "9.99", "price": "10.99" }
).
1
2
3
4
5
6
%dw 2.0
var myRead =
read("<prices><price>9.99</price><price>10.99</price></prices>","application/xml")
output application/json
---
myRead.prices groupBy "costs"
1
{ "costs" : { "price": "9.99", "price": "10.99" } }
groupBy(Null, (Nothing, Nothing) → Any): Null
Helper function that allows groupBy to work with null values.
1.1.17. isBlank
isBlank(String | Null): Boolean
Returns true
if the given string is empty or completely composed of whitespace,
false
if not.
Parameters
Name | Description |
---|---|
|
A input string to evaluate. |
Example
This example indicates whether the given values are blank.
1
2
3
4
%dw 2.0
output application/json
---
{ empty : isBlank(""), spaces : isBlank(" "), text : isBlank(" 1223") }
1
{ "empty": true, "spaces": true, "text": false }
1.1.18. 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.19. 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.20. 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.21. isInteger
isInteger(Number): Boolean
Returns true
if the given number is an integer (which lacks decimals),
false
if not.
Parameters
Name | Description |
---|---|
|
The number to evaluate. |
Example
This example indicates whether the input is an integer. Note numbers within strings get coerced to numbers.
1
2
3
4
%dw 2.0
output application/json
---
[ isLeapYear(locDT1), isLeapYear(locDT2), isInteger("1") ]
1
[ false, true, true ]
1.1.22. 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.23. 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.24. joinBy
joinBy(Array<Any>, 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.25. log
log(String, T): T
Without changing the value of the input, log
returns the input as a system
log.
This function can be used to debug DataWeave scripts until a proper
debugger is incorporated. The Logger component outputs the results
through DefaultLoggingService
through the Logger component
Parameters
Name | Description |
---|---|
|
A string that typically describes the log. |
|
The value to log. |
Example
This example logs the specified message. The DefaultLoggingService
for the
Logger component returns the message
WARNING - "Houston, we have a problem."
In
the console, while the component’s LoggerMessageProcessor
simply returns
"Houston, we have a problem."
, without the WARNING
prefix.
1
2
3
4
%dw 2.0
output application/json
---
"WARNING" log("Houston, we have a problem.")
1
WARNING - "Houston, we have a problem."
1.1.26. lower
lower(String): String
Returns the provided string in lowercase characters.
Parameters
Name | Description |
---|---|
|
The input string. |
Parameters
Name | Description |
---|---|
|
A string. |
Example
This example converts uppercase characters to lower-case.
1
2
3
4
%dw 2.0
output application/json
---
{ "name" : lower("MULESOFT") }
1
{ "name": "mulesoft" }
lower(Null): Null
Helper function that allows lower to work with null values.
1.1.27. 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 a input array (["jose", "pedro", "mateo"]
) to
produce an array of 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 $
, so the first
example can be written as shown next. Note that the concatenation function
(++
) in the mapping expression is written in prefix notation so that the
reference of both anonymous parameters can be read.
1
2
3
4
%dw 2.0
output application/json
---
['joe', 'pete', 'matt'] map ++(($$ + 1) ++ '_', $)
1
[ "1_joe", "2_pete", "3_matt" ]
map(Null, (item: Nothing, index: Nothing) → Any): Null
Helper function that allows map
to work with null
values.
1.1.28. 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: Number) → Nothing): Null
Helper function that allows mapObject
to work with null values.
1.1.29. match
match(String, Regex): Array<String>
Uses a 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
---
(upper("me@mulesoft.com") match /([a-z]*)@([a-z]*).com/)
1
[ "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.30. 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.31. max
max(Array<T>): T | Null
Returns the highest numeric value in an array.
Returns null if the array is empty and produces an error when non-numeric values are in the array.
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.32. maxBy
maxBy(Array<T>, (item: T) → Comparable): T | Null
Iterates over an array and returns the highest value of comparable elements from it.
The items need to be of the same type. maxBy
returns an error if they are
not, and it returns null when the array is empty.
Parameters
Name | Description |
---|---|
|
The input array. |
|
Expression for selecting an item from the array, where the item is a |
Example
This example returns the greatest numeric value within objects
(key-value pairs) in an array. Notice that it uses item.a
to select the
value of the object. You can also write the same expression like this, using
an anonymous parameter:
[ { "a" : 1 }, { "a" : 3 }, { "a" : 2 } ] maxBy $.a
1
2
3
4
%dw 2.0
output application/json
---
[ { "a" : 1 }, { "a" : 3 }, { "a" : 2 } ] maxBy ((item) -> item.a)
1
{ "a" : 3 }
Example
This example gets the latest DateTime
, Date
, and Time
from inputs
defined in the variables myDateTime1
and myDateTime2
. It also shows that
the function returns null on an empty array.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
var myDateTime1 = "2017-10-01T22:57:59-03:00"
var myDateTime2 = "2018-10-01T23:57:59-03:00"
output application/json
---
{
myMaxBy: {
byDateTime: [ myDateTime1, myDateTime2 ] maxBy ((item) -> item),
byDate: [ myDateTime1 as Date, myDateTime2 as Date ] maxBy ((item) -> item),
byTime: [ myDateTime1 as Time, myDateTime2 as Time ] maxBy ((item) -> item),
emptyArray: [] maxBy ((item) -> item)
}
}
1
2
3
4
5
6
7
8
{
"myMaxBy": {
"byDateTime": "2018-10-01T23:57:59-03:00",
"byDate": "2018-10-01",
"byTime": "23:57:59-03:00",
"emptyArray": null
}
}
1.1.33. min
min(Array<T>): T | Null
Returns the lowest numeric value in an array.
Returns null if the array is empty and produces an error when non-numeric values are in the array.
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.34. 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.35. 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.36. native
native(String): Nothing
Internal method used to indicate that a function implementation is not written in DataWeave but in Scala.
1.1.37. 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
DataTime
value.
1
2
3
4
%dw 2.0
output application/json
---
{ nowCalled: now() }
1
{ "nowCalled": "2018-11-26T18:23:06.773-03: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
.
See also,
DataWeave Selectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
%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
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"now": "2018-07-23T22:03:04.829Z",
"epochTime": 1533143270,
"nanoseconds": 829000000,
"milliseconds": 829,
"seconds": 4,
"minutes": 3,
"hour": 22,
"day": 23,
"month": 7,
"year": 2018,
"quarter": 3,
"dayOfWeek": 1,
"dayOfYear": 204,
"offsetSeconds": 0
}
1.1.38. 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
---
{ orderByLetter: [{ letter: "e" }, { letter: "d" }] } orderBy($.letter)
1
{ "orderByLetter": [ { "letter": "d" }, { "letter": "e" } ] }
Example
The orderBy
function does not have an option to order in descending order
instead of ascending. In these cases, you can simply invert the order of
the resulting array using -
, for example:
1
2
3
4
%dw 2.0
output application/json
---
orderDescending: ([3,8,1] orderBy -$)
1
{ "orderDescending": [8,3,1] }
orderBy(Array<T>, (item: T, index: Number) → R): Array<T>
Sorts an array using the specified criteria.
Parameters
Name | Description |
---|---|
|
The array to sort. |
|
The result of the function will be used as the criteria to sort the list. It should return a simple value (String, Number, etc) |
Example
This example sorts an array of numbers based on the numeric values.
1
2
3
4
%dw 2.0
output application/json
---
[3,2,3] orderBy $
1
[ 2, 3, 3 ]
Example
This example sorts an array of people based on their age.
1
2
3
4
%dw 2.0
output application/json
---
[{name: "Santiago", age: 42},{name: "Leandro", age: 29}, {name: "Mariano", age: 35}] orderBy (person) -> person.age
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
{
name: "Leandro",
age: 29
},
{
name: "Mariano",
age: 35
},
{
name: "Santiago",
age: 42
}
]
orderBy(Null, (item: Nothing, index: Nothing) → Null): Null
Helper function that allows orderBy to work with null values.
1.1.39. pluck
pluck({ (K)?: V }, (value: V, key: K, index: Number) → R): Array<R>
Useful for mapping an object into an array, pluck
iterates over an object
and returns an array of keys, values, or indices from the object.
It is an alternative to mapObject
, which is similar but returns
an object, instead of an array.
Parameters
Name | Description |
---|---|
|
The object to map. |
|
Expression or selector that provides the |
Example
This example iterates over { "a":"b","c":"d"}
using the
anonymous mapper function ((value,key,index) → { (index) : { (value):key} }
)
to invert each key-value pair in the specified object and to return their
indices as keys. The mapper uses named parameters to identify
the keys, values, and indices of the object. Note that you can write
the same expression using anonymous parameters, like this:
{"a":"b","c":"d"} pluck { ($$$) : { ($):$$} }
Unlike the almost identical example that uses mapObject
, pluck
returns
the output as an array.
1
2
3
4
%dw 2.0
output application/json
---
{"a":"b","c":"d"} pluck (value,key,index) -> { (index) : { (value):key} }
1
[ { "0": { "b": "a" }, "1": { "d": "c" } } ]
Example
This example uses pluck
to iterate over each element within <prices/>
and returns arrays of their keys, values, and indices. It uses anonymous
parameters to capture them. Note that it uses as Number
to convert the
values to numbers. Otherwise, they would return as strings.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
output application/json
var readXml = read("<prices>
<basic>9.99</basic>
<premium>53.00</premium>
<vip>398.99</vip>
</prices>", "application/xml")
---
"result" : {
"keys" : readXml.prices pluck($$),
"values" : readXml.prices pluck($) as Number,
"indices" : readXml.prices pluck($$$)
}
1
2
3
4
5
6
7
{
"result": {
"keys": [ "basic", "premium", "vip" ],
"values": [ 9.99, 53, 398.99 ],
"indices": [ 0, 1, 2 ]
}
}
pluck(Null, (value: Nothing, key: Nothing, index: Nothing) → Any): Null
Helper function that allows pluck to work with null values.
1.1.40. 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.41. 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.42. 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.43. 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 Formats Supported by DataWeave. |
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
5
6
<?xml version='1.0' encoding='UTF-8'?>
<XML>
<basic>9.99</basic>
<premium>53</premium>
<vip>398.99</vip>
</XML>
1.1.44. readUrl
readUrl(String, String, Object): Any
Similar to the read
function. However, readURL
accepts a URL, including
a classpath-based URL.
The classpath-based URL uses the classpath:`
protocol prefix, for example,
classpath://myfolder/myFile.txt
where myFolder
is located under
src/main/resources
in a Mule project. Otherwise, readURL
accepts
the same arguments as read
.
Parameters
Name | Description |
---|---|
|
The URL string to read. It also accepts a classpath-based URL. |
|
A supported format (or mime type). Default: |
|
Optional: Sets reader configuration properties. For other formats and reader configuration properties, see Formats Supported by DataWeave. |
Example
This example reads a JSON object from a URL. (For readability, the output
values shown below are shortened with …
.)
1
2
3
4
%dw 2.0
output application/json
---
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
1
{ "userId": 1, "id": 1, "title": "sunt aut ...", "body": "quia et ..." }
Example
This example reads a JSON object from a myJsonSnippet.json
file located in
the src/main/resources
directory in Studio. (Sample JSON content for that
file is shown in the Input section below.) After reading the file contents,
the script transforms selected fields from JSON to CSV. Reading files
in this way can be useful when trying out a DataWeave script on sample data,
especially when the source data is large and your script is complex.
1
2
3
4
5
%dw 2.0
var myJsonSnippet = readUrl("classpath://myJsonSnippet.json", "application/json")
output application/csv
---
(myJsonSnippet.results map(item) -> item.profile)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{
"results": [
{
"profile": {
"firstName": "john",
"lastName": "doe",
"email": "johndoe@demo.com"
},
"data": {
"interests": [
{
"language": "English",
"tags": [
"digital-strategy:Digital Strategy",
"innovation:Innovation"
],
"contenttypes": []
}
]
}
},
{
"profile": {
"firstName": "jane",
"lastName": "doe",
"email": "janedoe@demo.com"
},
"data": {
"interests": [
{
"language": "English",
"tags": [
"tax-reform:Tax Reform",
"retail-health:Retail Health"
],
"contenttypes": [
"News",
"Analysis",
"Case studies",
"Press releases"
]
}
]
}
}
]
}
1
2
3
firstName,lastName,email
john,doe,johndoe@demo.com
jane,doe,janedoe@demo.com
Example
This example reads a simple dwl
file from the src/main/resources
directory in Studio, then dynamically reads the value of the key name
from it. (Sample content for the input file is shown in the Input
section below.)
1
2
3
4
%dw 2.0
output application/json
---
(readUrl("classpath://name.dwl", "application/dw")).firstName
1
2
3
4
{
"firstName" : "Somebody",
"lastName" : "Special"
}
1
"Somebody"
1.1.45. 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 12
(= 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": 12, "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.46. 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.47. 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.48. 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.49. 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 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 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.50. 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
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.51. 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.52. 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 also use the startsWith(text,prefix)
notation (for example,
startsWith("Mari","Mar")
).
1
2
3
4
%dw 2.0
output application/json
---
[ "Mari" startsWith("Mar"), "Mari" startsWith("Em") ]
1
[ true, false ]
1.1.53. 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.54. 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.55. 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 long text" }
Example
This example shows how trim
handles a variety strings and how it
handles a null value.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
---
{
"null": trim(null),
"empty": trim(""),
"blank": trim(" "),
"noBlankSpaces": trim("abc"),
"withSpaces": trim(" abc ")
}
1
2
3
4
5
6
7
{
"null": null,
"empty": "",
"blank": "",
"noBlankSpaces": "abc",
"withSpaces": "abc"
}
trim(Null): Null
Helper function that allows trim to work with null values.
1.1.56. 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.57. 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 are not all the same. The function only creates 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.58. upper
upper(String): String
Returns the provided string in uppercase characters.
Parameters
Name | Description |
---|---|
|
The string to convert to uppercase. |
Example
This example converts lowercase characters to uppercase.
1
2
3
4
%dw 2.0
output application/json
---
{ "name" : upper("mulesoft") }
1
{ "name": "MULESOFT" }
upper(Null): Null
Helper function that allows trim to work with null values.
1.1.59. 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.60. with
with(((V, U) → R) → X, (V, U) → R): X
When used with replace
, with
passes a replacement string.
Parameters
Name | Description |
---|---|
|
The value to be replaced. |
|
The replacement value for the input value. |
Example
This example replaces all numbers in a string with "x" characters.
1
2
3
4
%dw 2.0
output application/json
---
{ "ssn" : "987-65-4321" replace /[0-9]/ with("x") }
1
{ "ssn": "xxx-xx-xxxx" }
1.1.61. 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 Formats Supported by DataWeave. |
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.62. 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. Since Version: 2.2.0
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. Time
A time in a specific TimeZone
. For example: |22:10:18Z|
1
Time
1.2.28. TimeZone
A time zone.
1
TimeZone
1.2.29. Type
A type in the DataWeave type system.
1
Type
1.2.30. Uri
A URI.
1
Uri
1.3. Annotations
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 input content, a |
|
The secret cryptographic key (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 input content, a |
|
The secret cryptographic key (a |
|
(Since Version: 2.2.0) The hashing algorithm. By default "HmacSHA1" is used. Other valid values are "HmacSHA256" and "HmacSHA512". |
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
---
{ "HMACWith" : Crypto::HMACWith("key_re_loca" as Binary, "xxxxx" as Binary) }
1
{ "HMACWith": "2e2da2e51286db8afa9900f51218529cda3dd32a" }
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 of binary content with a specified algorithm.
You can use these names as algorithm
arguments:
Name | Description |
---|---|
MD2 |
The MD2 message digest algorithm as defined in RFC 1319[http://www.ietf.org/rfc/rfc1319.txt]. |
MD5 |
The MD5 message digest algorithm as defined in RFC 1321[http://www.ietf.org/rfc/rfc1321.txt]. |
SHA-1, SHA-256, SHA-384, SHA-512 |
Hash algorithms defined in the FIPS PUB 180-2 [http://csrc.nist.gov/publications/fips/index.html]. SHA-256 is a 256-bit hash function intended to provide 128 bits of security against collision attacks, while SHA-512 is a 512-bit hash function intended to provide 256 bits of security. A 384-bit hash may be obtained by truncating the SHA-512 output. |
Parameters
Name | Description |
---|---|
|
A binary input value to encrypt. |
|
The name of the algorithm to use for encrypting the |
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, "SHA-256") }
1
{ "md2": "\ufffd\u0004ls\ufffd\u00031\ufffdh\ufffd}8\u0004\ufffd\u0006U" }
3. dw::Runtime
This module contains functions that allow you to interact with the DataWeave engine.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::Runtime
to the header of your
DataWeave script.
3.1. Functions
3.1.1. fail
fail(String): Nothing
Throws an exception with the specified message.
Parameters
Name | Description |
---|---|
|
An error message ( |
Example
This example returns a failure message Data was empty
because the expression
(sizeOf(myVar) ⇐ 0)
is true
. A shortened version of the error message
is shown in the Output section below.
1
2
3
4
5
6
%dw 2.0
import * from dw::Runtime
var result = []
output application/json
---
if(sizeOf(result) <= 0) fail('Data was empty') else result
1
2
3
4
ERROR 2018-07-29 11:47:44,983 ...
*********************************
Message : "Data was empty
...
3.1.2. failIf
failIf(T, (value: T) → Boolean, String): T
Produces an error with the specified message if the expression in
the evaluator returns true
, otherwise returns the value.
Parameters
Name | Description |
---|---|
|
The value to return only if the |
|
Expression that returns |
Example
This example produces a runtime error (instead of a SUCCESS message) because
the expression isEmpty(result)
is true
. It is true
because an empty
object is passed through variable result
.
1
2
3
4
5
6
%dw 2.0
import failIf from dw::Runtime
var result = {}
output application/json
---
{ "result" : "SUCCESS" failIf (isEmpty(result)) }
1
2
3
ERROR 2018-07-29 11:56:39,988 ...
**********************************
Message : "Failed
3.1.3. locationString
locationString(Any): String
Returns the location string of a given value.
Parameters
Name | Description |
---|---|
|
A value of any type. |
Example
This example returns the contents of the line (the location) that defines
variable a
in the header of the DataWeave script.
1
2
3
4
5
6
%dw 2.0
import * from dw::Runtime
output application/json
var a = 123
---
locationString(a)
1
"var a = 123"
3.1.4. orElse
orElse(TryResult<T>, () → R): T | R
Returns the result of the orElse
if the previous
try result failed if not returns the result of the previous
Since Version: 2.2.0
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
11
%dw 2.0
import * from dw::Runtime
var user = {}
var otherUser = {name: "DW"}
---
{
a: try(() -> user.name!) orElse "No User Name",
b: try(() -> otherUser.name) orElse "No User Name"
}
1
2
3
4
{
"a": "No User Name",
"b": "DW"
}
3.1.5. orElseTry
orElseTry(TryResult<T>, () → R): TryResult<T | R>
Function to be use with try in order to chain multiple try
Since Version: 2.2.0
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 = {}
---
{
a: try(() -> user.name!) orElseTry otherUser.name!,
b: try(() -> user.name!) orElseTry "No User Name"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"a": {
"success": false,
"error": {
"kind": "KeyNotFoundException",
"message": "There is no key named 'name'",
"location": "\n9| a: try(() -> user.name!) orElseTry otherUser.name!,\n ^^^^^^^^^^^^^^",
"stack": [
"main (org::mule::weave::v2::engine::transform:9:40)"
]
}
},
"b": {
"success": true,
"result": "No User Name"
}
}
3.1.6. prop
prop(String): String | Null
Returns the value of the property with the specified name or null
if the
property is not defined.
Parameters
Name | Description |
---|---|
|
The property to retrieve. |
Example
This example gets the user.timezone
property.
1
2
3
4
5
%dw 2.0
import * from dw::Runtime
output application/dw
---
{ "props" : prop("user.timezone") }
1
{ props: "America/Los_Angeles" as String {class: "java.lang.String"} }
3.1.7. props
props(): Dictionary<String>
Returns all the properties configured for Mule runtime.
Example
This example returns all properties from the java.util.Properties
class.
1
2
3
4
5
%dw 2.0
import * from dw::Runtime
output application/dw
---
{ "props" : props() }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
{
props: {
"java.vendor": "Oracle Corporation" as String {class: "java.lang.String"},
"sun.java.launcher": "SUN_STANDARD" as String {class: "java.lang.String"},
"sun.management.compiler": "HotSpot 64-Bit Tiered Compilers" as String ..., * "os.name": "Mac OS X" as String {class: "java.lang.String"},
"sun.boot.class.path": "/Library/Java/JavaVirtualMachines/ ...,
"org.glassfish.grizzly.nio.transport.TCPNIOTransport...": "1048576" ...,
"java.vm.specification.vendor": "Oracle Corporation" as String ...,
"java.runtime.version": "1.8.0_111-b14" as String {class: "java.lang.String"},
"wrapper.native_library": "wrapper" as String {class: "java.lang.String"},
"wrapper.key": "XlIl4YartmfEU3oKu7o81kNQbwhveXi-" as String ...,
"user.name": "me" as String {class: "java.lang.String"},
"mvel2.disable.jit": "TRUE" as String {class: "java.lang.String"},
"user.language": "en" as String {class: "java.lang.String"} ...,
"sun.boot.library.path": "/Library/Java/JavaVirtualMachines ...
"xpath.provider": "com.mulesoft.licm.DefaultXPathProvider" ...,
"wrapper.backend": "pipe" as String {class: "java.lang.String"},
"java.version": "1.8.0_111" as String {class: "java.lang.String"},
"user.timezone": "America/Los_Angeles" as String {class: "java.lang.String"},
"java.net.preferIPv4Stack": "TRUE" as String {class: "java.lang.String"},
"sun.arch.data.model": "64" as String {class: "java.lang.String"},
"java.endorsed.dirs": "/Library/Java/JavaVirtualMachines/...,
"sun.cpu.isalist": "" as String {class: "java.lang.String"},
"sun.jnu.encoding": "UTF-8" as String {class: "java.lang.String"},
"mule.testingMode": "" as String {class: "java.lang.String"},
"file.encoding.pkg": "sun.io" as String {class: "java.lang.String"},
"file.separator": "/" as String {class: "java.lang.String"},
"java.specification.name": "Java Platform API Specification" ...,
"java.class.version": "52.0" as String {class: "java.lang.String"},
"jetty.git.hash": "82b8fb23f757335bb3329d540ce37a2a2615f0a8" ...,
"user.country": "US" as String {class: "java.lang.String"},
"mule.agent.configuration.folder": "/Applications/AnypointStudio.app/ ...,
"log4j.configurationFactory": "org.apache.logging.log4j.core...",
"java.home": "/Library/Java/JavaVirtualMachines/...,
"java.vm.info": "mixed mode" as String {class: "java.lang.String"},
"wrapper.version": "3.5.34-st" as String {class: "java.lang.String"},
"os.version": "10.13.4" as String {class: "java.lang.String"},
"org.eclipse.jetty.LEVEL": "WARN" as String {class: "java.lang.String"},
"path.separator": ":" as String {class: "java.lang.String"},
"java.vm.version": "25.111-b14" as String {class: "java.lang.String"},
"wrapper.pid": "5212" as String {class: "java.lang.String"},
"java.util.prefs.PreferencesFactory": "com.mulesoft.licm..."},
"wrapper.java.pid": "5213" as String {class: "java.lang.String"},
"mule.home": "/Applications/AnypointStudio.app/...,
"java.awt.printerjob": "sun.lwawt.macosx.CPrinterJob" ...,
"sun.io.unicode.encoding": "UnicodeBig" as String {class: "java.lang.String"},
"awt.toolkit": "sun.lwawt.macosx.LWCToolkit" ...,
"org.glassfish.grizzly.nio.transport...": "1048576" ...,
"user.home": "/Users/me" as String {class: "java.lang.String"},
"java.specification.vendor": "Oracle Corporation" ...,
"java.library.path": "/Applications/AnypointStudio.app/...,
"java.vendor.url": "http://java.oracle.com/" as String ...,
"java.vm.vendor": "Oracle Corporation" as String {class: "java.lang.String"},
gopherProxySet: "false" as String {class: "java.lang.String"},
"wrapper.jvmid": "1" as String {class: "java.lang.String"},
"java.runtime.name": "Java(TM) SE Runtime Environment" ...,
"mule.encoding": "UTF-8" as String {class: "java.lang.String"},
"sun.java.command": "org.mule.runtime.module.reboot....",
"java.class.path": "%MULE_LIB%:/Applications/AnypointStudio.app...",
"log4j2.loggerContextFactory": "org.mule.runtime.module.launcher...,
"java.vm.specification.name": "Java Virtual Machine Specification" ,
"java.vm.specification.version": "1.8" as String {class: "java.lang.String"},
"sun.cpu.endian": "little" as String {class: "java.lang.String"},
"sun.os.patch.level": "unknown" as String {class: "java.lang.String"},
"com.ning.http.client.AsyncHttpClientConfig.useProxyProperties": "true" ...,
"wrapper.cpu.timeout": "10" as String {class: "java.lang.String"},
"java.io.tmpdir": "/var/folders/42/dd73l3rx7qz0n625hr29kty80000gn/T/" ...,
"anypoint.platform.analytics_base_uri": ...,
"java.vendor.url.bug": "http://bugreport.sun.com/bugreport/" ...,
"os.arch": "x86_64" as String {class: "java.lang.String"},
"java.awt.graphicsenv": "sun.awt.CGraphicsEnvironment" ...,
"mule.base": "/Applications/AnypointStudio.app...",
"java.ext.dirs": "/Users/staceyduke/Library/Java/Extensions: ..."},
"user.dir": "/Applications/AnypointStudio.app/..."},
"line.separator": "\n" as String {class: "java.lang.String"},
"java.vm.name": "Java HotSpot(TM) 64-Bit Server VM" ...,
"org.quartz.scheduler.skipUpdateCheck": "true" ...,
"file.encoding": "UTF-8" as String {class: "java.lang.String"},
"mule.forceConsoleLog": "" as String {class: "java.lang.String"},
"java.specification.version": "1.8" as String {class: "java.lang.String"},
"wrapper.arch": "universal" as String {class: "java.lang.String"}
} as Object {class: "java.util.Properties"}
3.1.8. try
try(() → T): TryResult<T>
Evaluates the delegate function and returns an object with the result or an error message.
Parameters
Name | Description |
---|---|
|
The function to evaluate. |
Example
This example passes the fail
function as an argument to try
.
1
2
3
4
5
%dw 2.0
import try, fail from dw::Runtime
output application/json
---
try(fail)
1
2
3
4
5
6
7
8
9
10
11
{
"success": false,
"error": {
"kind": "UserException",
"message": "Error",
"location": "Unknown location",
"stack": [
"main (anonymous:0:0)"
]
}
}
3.1.9. wait
wait(T, Number): T
Stops the execution for the specified timeout (in milliseconds).
WARNING
Stopping the execution will block the thread used, potentially causing slowness, low performance and potentially freezes of the entire runtime. This operation is intented for limited functional testing purposes and should not be used in production application, performance testing or with multiple applications deployed.
Parameters
Name | Description |
---|---|
|
Input of any type. |
|
The number of milliseconds to wait. |
Example
This example waits 2000 milliseconds (2 seconds) to execute.
1
2
3
4
5
%dw 2.0
import * from dw::Runtime
output application/json
---
{ "user" : 1 } wait 2000
1
{ "user": 1 }
3.2. Types
3.2.1. TryResult
Object with a result or error message. If success
is false
, it contains
the error
. If true
, it provides the result
.
1
{ success: Boolean, result?: T, error?: { kind: String, message: String, stack?: Array<String>, location?: String } }
4. dw::System
This module contains functions that allow you to interact with the underlying system.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::System
to the header of your
DataWeave script.
4.1. Functions
4.1.1. envVar
envVar(String): String | Null
Returns an environment variable with the specified name or null
if the
environment variable is not defined.
Parameters
Name | Description |
---|---|
|
Provides the name of the environment variable. |
Example
This example returns a Mac command console (SHELL
) path and returns null
on FAKE_ENV_VAR
(an undefined environment variable). SHELL
is one of the
standard Mac environment variables. Also notice that the import
command
enables you to call the function without prepending the module name to it.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::System
output application/json
---
{
"envVars" : [
"real" : envVar("SHELL"),
"fake" : envVar("FAKE_ENV_VAR")
]
}
1
2
3
4
5
6
7
8
"envVars": [
{
"real": "/bin/bash"
},
{
"fake": null
}
]
4.1.2. envVars
envVars(): Dictionary<String>
Returns all of the environment variables defined in the host system.
Example
This example returns a Mac command console (SHELL
) path. SHELL
is one of
the standard Mac environment variables. To return all the environment
variables, you can use dw::System::envVars()
.
1
2
3
4
5
%dw 2.0
import dw::System
output application/json
---
{ "envVars" : dw::System::envVars().SHELL }
1
{ "envVars": "/bin/bash" }
5. dw::core::Arrays
This module contains helper functions for working with arrays.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Arrays
to the header of your
DataWeave script.
5.1. Functions
5.1.1. countBy
countBy(Array<T>, (T) → Boolean): Number
Counts the elements in a list (array) that match the results of a function.
Parameters
Name | Description |
---|---|
|
The input array that contains elements to match. |
|
A function to apply to elements in the input array. |
Example
This counts the values in the array that are equal to the result of the
matchingFunction
((($ mod 2) == 0)
).
1
2
3
4
5
%dw 2.0
import * from dw::core::Arrays
output application/json
---
{ "countBy" : [1, 2, 3, 4] countBy (($ mod 2) == 0) }
1
{ "countBy": 2 }
5.1.2. divideBy
divideBy(Array<T>, Number): Array<Array<T>>
Breaks up a list (array) into sub-lists (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 first n
elements. It returns the original array when n ⇐ 0
and an empty array when n > sizeOf(array)
.
Since Version: 2.2.0 ===== Parameters
Name | Description |
---|---|
|
The left Array of elements. |
|
The number of elements to take. |
Example
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.
Since Version: 2.2.0 ===== Parameters
Name | Description |
---|---|
|
The Array of elements. |
|
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 arr = [0,1,2,3,4,5]
---
arr dropWhile $ <= 2
1
2
3
4
5
[
3,
4,
5
]
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 ]
}
]
}
5.1.6. indexOf
indexOf(Array<T>, T): Number
Returns the index of the first occurrence of an element within the array.
Since Version: 2.2.0 ===== Parameters
Name | Description |
---|---|
|
The Array of elements. |
|
The element to find. |
Example
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.7. 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.
Since Version: 2.2.0
Parameters
Name | Description |
---|---|
|
The Array of elements. |
|
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"]
---
users indexWhere (item) -> item startsWith "Jul"
1
2
5.1.8. join
join(Array<L>, Array<R>, (leftValue: L) → String, (rightValue: R) → String): Array<Pair<L, R>>
Joins two array of objects by a given ID
criteria.
It will return an Array of object containing only the ones that the ID
of the left
can be matched with an ID
of the right
.
Since Version: 2.2.0 ===== Parameters
Name | Description |
---|---|
|
The left Array of objects. |
|
The right 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
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.9. leftJoin
leftJoin(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.
It will return an Array all the left
items merged by ID
with the right items in the case where it exists any.
Since Version: 2.2.0 ===== Parameters
Name | Description |
---|---|
|
The left Array of objects. |
|
The right 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
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.10. 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.
It will return an Array with all the left
items merged by ID
with the left
items in the case where it exists any, and the right
items that are not present in the left
Since Version: 2.2.0 ===== Parameters
Name | Description |
---|---|
|
The left Array of objects. |
|
The right 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
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.11. partition
partition(Array<T>, (item: T) → Boolean): { success: Array<T>, failure: Array<T> }
Separates the array into the elements that satisfy the condition and those which don’t.
Since Version: 2.2.0 ===== 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 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.12. slice
slice(Array<T>, Number, Number): Array<T>
Selects the interval of elements that satisfy the condition: from ⇐ indexOf(array) < until
Since Version: 2.2.0 ===== Parameters
Name | Description |
---|---|
|
The Array of elements. |
|
The lowest index to include from the array. |
|
The lowest index to exclude from the array. |
Example
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.13. some
some(Array<T>, (T) → Boolean): Boolean
Returns true
if an element in the array matches the specified condition.
The function stops iterating after the first match to an element in the array.
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 in 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
output application/json
---
{ "results" : [
"ok" : [
[1,2,3] some (($ mod 2) == 0),
[1,2,3] some (($ mod 2) == 1),
[1,2,3,4,5,6,7,8] some (log('should stop at 2 ==', $) == 2),
[1,2,3] some ($ == 1),
[1,1,1] 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 ]
},
{
"err": [ false, false ]
}
]
}
5.1.14. splitAt
splitAt(Array<T>, Number): Pair<Array<T>, Array<T>>
Splits an array into two at a given position.
Since Version: 2.2.0 ===== Parameters
Name | Description |
---|---|
|
The Array of elements. |
|
The index to split at. |
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.15. 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.
Since Version: 2.2.0 ===== 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.16. 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.17. take
take(Array<T>, Number): Array<T>
Selects first n
elements. It returns an empty array when n ⇐ 0
and the original array when n > sizeOf(array)
.
Since Version: 2.2.0 ===== Parameters
Name | Description |
---|---|
|
The left Array of elements. |
|
The number of elements to take. |
Example
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.18. takeWhile
takeWhile(Array<T>, (item: T) → Boolean): Array<T>
Takes elements for the array while the condition is met.
Since Version: 2.2.0 ===== Parameters
Name | Description |
---|---|
|
The Array of elements. |
|
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 arr = [0,1,2,3,4,5,1]
---
arr takeWhile $ <= 2
1
2
3
4
5
[
0,
1,
2
]
6. dw::core::Binaries
This module contains helper functions for working with binaries.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Binaries
to the header of your
DataWeave script.
6.1. Functions
6.1.1. fromBase64
fromBase64(String): Binary
Transforms a Base64 string into a binary value.
Parameters
Name | Description |
---|---|
|
The Base64 string to transform. |
Example
This example takes a Base64 string and transforms it into a binary.
1
2
3
4
5
%dw 2.0
import * from dw::core::Binaries
output application/json
---
{ "BinaryFromBase64" : fromBase64("TXVsZQ==") }
1
{ "BinaryFromBase64": "Mule" }
6.1.2. fromHex
fromHex(String): Binary
Transforms a hexadecimal string into a binary.
Parameters
Name | Description |
---|---|
|
A hexadecimal string to transform. |
Example
This example transforms a hexadecimal string to "Mule".
1
2
3
4
5
%dw 2.0
import * from dw::core::Binaries
output application/json
---
{ "hexToBinary": fromHex("4D756C65") }
1
{ "hexToBinary": "Mule" }
6.1.3. readLinesWith
readLinesWith(Binary, String): Array<String>
Splits the specified Binary content into lines and returns the results in an array.
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
), into 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 to Base64.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Binaries
var myBinary = "Mule" as Binary
output application/json
---
{ "BinaryToBase64" : toBase64(myBinary) }
1
{ "BinaryToBase64": "TXVsZQ==" }
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.
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 Number.
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.
Since Version: 2.2.0
7.1. Functions
7.1.1. fromBinary
fromBinary(String): Number
Transforms from a binary number into a decimal number
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `binaryText` | The binary number represented in a `String` |===
Example
This example shows how the toBinary
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import fromBinary from dw::core::Numbers
---
{
a: fromBinary("-10"),
b: fromBinary("11111000111010111010110100101011100001001110000011010101100010111101001011100000100010011000011101100101101001111101111010110010010100110010100100000000000000000000000000000000000000000000000000000000000000"),
c: fromBinary(0),
d: fromBinary(null),
e: fromBinary("100"),
}
1
2
3
4
5
6
7
{
"a": -2,
"b": 100000000000000000000000000000000000000000000000000000000000000,
"c": 0,
"d": null,
"e": 4
}
fromBinary(Null): Null
Helper function to make fromBinary
work with null value
7.1.2. fromHex
fromHex(String): Number
Transforms a hexadecimal number into decimal number.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `hexText` | The hexadecimal number represented in a `String`. |===
Example
This example shows how the toBinary
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import fromHex from dw::core::Numbers
---
{
a: fromHex("-1"),
b: fromHex("3e3aeb4ae1383562f4b82261d969f7ac94ca4000000000000000"),
c: fromHex(0),
d: fromHex(null),
e: fromHex("f"),
}
1
2
3
4
5
6
7
{
"a": -1,
"b": 100000000000000000000000000000000000000000000000000000000000000,
"c": 0,
"d": null,
"e": 15
}
fromHex(Null): Null
Helper function to make fromHex
work with null value
7.1.3. fromRadixNumber
fromRadixNumber(String, Number): Number
Transforms a number in the specified radix into decimal number
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `numberText` | The number text | `radix` | The radix number |===
Example
This example shows how the fromRadixNumber
behaves under different inputs.
1
2
3
4
5
6
7
%dw 2.0
import fromRadixNumber from dw::core::Numbers
---
{
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 one.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `number` | The input number. |===
Example
This example shows how the toBinary
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import toBinary from dw::core::Numbers
---
{
a: toBinary(-2),
b: toBinary(100000000000000000000000000000000000000000000000000000000000000),
c: toBinary(0),
d: toBinary(null),
e: toBinary(2),
}
1
2
3
4
5
6
7
{
"a": "-10",
"b": "11111000111010111010110100101011100001001110000011010101100010111101001011100000100010011000011101100101101001111101111010110010010100110010100100000000000000000000000000000000000000000000000000000000000000",
"c": "0",
"d": null,
"e": "10"
}
toBinary(Null): Null
Helper function to make toBinary
work with null value.
7.1.5. toHex
toHex(Number): String
Transforms a decimal number into a hexadecimal one.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `number` | The input number. |===
Example
This example shows how the toHex
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import toHex from dw::core::Numbers
---
{
a: toHex(-1),
b: toHex(100000000000000000000000000000000000000000000000000000000000000),
c: toHex(0),
d: toHex(null),
e: toHex(15),
}
1
2
3
4
5
6
7
{
"a": "-1",
"b": "3e3aeb4ae1383562f4b82261d969f7ac94ca4000000000000000",
"c": "0",
"d": null,
"e": "f"
}
toHex(Null): Null
Helper function to make toHex
work with null value.
7.1.6. toRadixNumber
toRadixNumber(Number, Number): String
Transforms a decimal number into a number string in other radix
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `number` | The decimal number | `radix` | The radix of the result number |===
Example
This example shows how the toRadixNumber
behaves under different inputs.
1
2
3
4
5
6
7
%dw 2.0
import toRadixNumber from dw::core::Numbers
---
{
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)
Returns an array of key-value pairs that describe the key, value, and any attributes in the input object.
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. keySet
keySet(T): ?
Returns an array of key names from an object.
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.4. mergeWith
mergeWith(T, V): ?
Appends any key-value pairs from a source object to a target object.
If source and target objects have the same key, the function appends that source object to the target and removes that target object from the output.
Parameters
Name | Description |
---|---|
|
The object to append to the |
|
The object to which the |
Example
This example appends the source objects to the target. Notice that
"a" : true,
is removed from the output, and "a" : false
is appended
to the target.
1
2
3
4
5
%dw 2.0
import mergeWith from dw::core::Objects
output application/json
---
{ "mergeWith" : { "a" : true, "b" : 1} mergeWith { "a" : false, "c" : "Test"} }
1
2
3
4
5
"mergeWith": {
"b": 1,
"a": false,
"c": "Test"
}
mergeWith(Null, T): T
Helper method to make mergeWith
null friendly.
mergeWith(T, Null): T
Helper method to make mergeWith
null friendly.
8.1.5. nameSet
nameSet(Object): Array<String>
Returns an array of keys from an object.
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.6. valueSet
valueSet({ (K)?: V }): Array<V>
Returns an array of the values from key-value pairs in an object.
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 dw::core::Objects
output application/json
---
{ "valueSet" : valueSet({a: true, b: 1}) }
1
{ "valueSet" : [true,1] }
9. 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.
9.1. Functions
9.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
.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. | `prefix` | the text used as prefix. |===
Example
This example shows how the appendIfMissing
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import appendIfMissing from dw::core::Strings
---
{
"a": appendIfMissing(null, ""),
"b": appendIfMissing("abc", ""),
"c": appendIfMissing("", "xyz") ,
"d": appendIfMissing("abc", "xyz") ,
"e": appendIfMissing("abcxyz", "xyz")
}
1
2
3
4
5
6
7
{
"a": null,
"b": "abc",
"c": "xyz",
"d": "abcxyz",
"e": "abcxyz"
}
appendIfMissing(Null, String): Null
Helper function to make appendIfMissing
work with null
value.
9.1.2. camelize
camelize(String): String
Returns a string in camel case based on underscores in 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
%dw 2.0
import * from dw::core::Strings
output application/json
---
{ "camelize" : camelize("customer_first_name") }
1
{ "camelize" : "customerFirstName" }
camelize(Null): Null
Helper function that allows camelize
to work with null values.
9.1.3. capitalize
capitalize(String): String
Capitalizes the first letter of each word in a string.
It also removes underscores between words and puts a space before each capitalized word.
Parameters
Name | Description |
---|---|
|
The string to capitalize. |
Example
This example capitalizes a set of strings.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a" : capitalize("customer"),
"b" : capitalize("customer_first_name"),
"c" : capitalize("customer NAME"),
"d" : capitalize("customerName")
}
1
2
3
4
5
6
{
"a": "Customer",
"b": "Customer First Name",
"c": "Customer Name",
"d": "Customer Name"
}
capitalize(Null): Null
Helper function that allows capitalize to work with null values.
9.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 }
9.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 }
9.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
{
"a" : dasherize("customer"),
"b" : dasherize("customer_first_name"),
"c" : dasherize("customer NAME"),
"d" : dasherize("customerName")
}
1
2
3
4
5
6
{
"a": "customer",
"b": "customer-first-name",
"c": "customer-name",
"d": "customer-name"
}
dasherize(Null): Null
Helper function that allows dasherize to work with null values.
9.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" }
9.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.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. |===
Example
This example shows how the isNumeric
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import isAlpha from dw::core::Strings
---
{
"a": isAlpha(null),
"b": isAlpha(""),
"c": isAlpha(" "),
"d": isAlpha("abc"),
"e": isAlpha("ab2c"),
"f": isAlpha("ab-c")
}
1
2
3
4
5
6
7
8
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": false
}
isAlpha(Null): Boolean
Helper function for isAlpha
so it works with null
value.
9.1.9. isAlphanumeric
isAlphanumeric(String): Boolean
Checks if the text
contains only Unicode letters or digits.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. |===
Example
This example shows how the isAlphanumeric
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import isAlphanumeric from dw::core::Strings
---
{
"a": isAlphanumeric(null),
"b": isAlphanumeric(""),
"c": isAlphanumeric(" "),
"d": isAlphanumeric("abc"),
"e": isAlphanumeric("ab c"),
"f": isAlphanumeric("ab2c"),
"g": isAlphanumeric("ab-c")
}
1
2
3
4
5
6
7
8
9
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": true,
"g": false
}
isAlphanumeric(Null): Boolean
Helper function for isAlphanumeric
so it works with null
value.
9.1.10. isLowerCase
isLowerCase(String): Boolean
Checks if the text
contains only lowercase characters.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. |===
Example
This example shows how the isNumeric
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
import isLowerCase from dw::core::Strings
---
{
"a": isLowerCase(null),
"b": isLowerCase(""),
"c": isLowerCase(" "),
"d": isLowerCase("abc"),
"e": isLowerCase("aBC"),
"f": isLowerCase("a c"),
"g": isLowerCase("a1c"),
"h": isLowerCase("a/c")
}
1
2
3
4
5
6
7
8
9
10
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": false,
"g": false,
"h": false
}
isLowerCase(Null): Boolean
Helper function for isLowerCase
so it works with null
value.
9.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.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. |===
Example
This example shows how the isNumeric
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
%dw 2.0
import isNumeric from dw::core::Strings
---
{
"a": isNumeric(null),
"b": isNumeric(""),
"c": isNumeric(" "),
"d": isNumeric("123"),
"e": isNumeric("१२३"),
"f": isNumeric("12 3"),
"g": isNumeric("ab2c"),
"h": isNumeric("12-3"),
"i": isNumeric("12.3"),
"j": isNumeric("-123"),
"k": isNumeric("+123")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": true,
"f": false,
"g": false,
"h": false,
"i": false,
"j": false,
"k": false
}
isNumeric(Null): Boolean
Helper function for isNumeric
so it works with null
value.
9.1.12. isUpperCase
isUpperCase(String): Boolean
Checks if the text
contains only uppercase characters.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. |===
Example
This example shows how the isNumeric
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
import isUpperCase from dw::core::Strings
---
{
"a": isUpperCase(null),
"b": isUpperCase(""),
"c": isUpperCase(" "),
"d": isUpperCase("ABC"),
"e": isUpperCase("aBC"),
"f": isUpperCase("A C"),
"g": isUpperCase("A1C"),
"h": isUpperCase("A/C")
}
1
2
3
4
5
6
7
8
9
10
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": false,
"g": false,
"h": false
}
isUpperCase(Null): Boolean
Helper function for isLowerCase
so it works with null
value.
9.1.13. isWhitespace
isWhitespace(String): Boolean
Checks if the text
contains only whitespace.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. |===
Example
This example shows how the isWhitespace
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import isWhitespace from dw::core::Strings
---
{
"a": isWhitespace(null),
"b": isWhitespace(""),
"c": isWhitespace(" "),
"d": isWhitespace("abc"),
"e": isWhitespace("ab2c"),
"f": isWhitespace("ab-c")
}
1
2
3
4
5
6
7
8
{
"a": false,
"b": true,
"c": true,
"d": false,
"e": false,
"f": false
}
isWhitespace(Null): Boolean
Helper function for isWhitespace
so it works with null
value.
9.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.
Since Version: 2.2.0 ===== 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 the leftPad behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
import leftPad from dw::core::Strings
---
{
"a": leftPad(null, 3),
"b": leftPad("", 3),
"c": leftPad("bat", 5),
"d": leftPad("bat", 3),
"e": leftPad("bat", -1)
}
1
2
3
4
5
6
7
{
"a": null,
"b": " ",
"c": " bat",
"d": "bat",
"e": "bat"
}
leftPad(Null, Number, String): Null
Helper function to make leftPad
work with null
value.
9.1.15. ordinalize
ordinalize(Number): String
Returns a number as an ordinal, such as 1st
or 2nd
.
Parameters
Name | Description |
---|---|
|
An input number to return as an ordinal. |
Example
This example returns a variety of input numbers as ordinals.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a" : ordinalize(1),
"b": ordinalize(2),
"c": ordinalize(5),
"d": ordinalize(103)
}
1
2
3
4
5
6
{
"a": "1st",
"b": "2nd",
"c": "5th",
"d": "103rd"
}
ordinalize(Null): Null
Helper function that allows ordinalize
to work with null values.
9.1.16. pluralize
pluralize(String): String
Pluralizes a singular string.
If the input is already plural (for example, "boxes"), the output will match the input.
Parameters
Name | Description |
---|---|
|
The string to pluralize. |
Example
This example pluralizes the input string "box" to return "boxes".
1
2
3
4
5
%dw 2.0
import * from dw::core::Strings
output application/json
---
{ "pluralize" : pluralize("box") }
1
{ "pluralize" : "boxes" }
pluralize(Null): Null
Helper function that allows pluralize to work with null values.
9.1.17. prependIfMissing
prependIfMissing(String, String): String
Prepends the prefix
to the start of the string if the text
does not already start with it
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. | `prefix` | the text used as prefix. |===
Example
This example shows how the prependIfMissing
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import prependIfMissing from dw::core::Strings
---
{
"a": prependIfMissing(null, ""),
"b": prependIfMissing("abc", ""),
"c": prependIfMissing("", "xyz"),
"d": prependIfMissing("abc", "xyz"),
"e": prependIfMissing("xyzabc", "xyz")
}
1
2
3
4
5
6
7
{
"a": null,
"b": "abc",
"c": "xyz",
"d": "xyzabc",
"e": "xyzabc"
}
prependIfMissing(Null, String): Null
Helper function to make prependIfMissing
work with null
value.
9.1.18. repeat
repeat(String, Number): String
Repeats a text
the amount of specified times
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. | `times` | number of times to repeat char, negative treated as zero |===
Example
This example shows how the repeat
behaves under different inputs and sizes.
1
2
3
4
5
6
7
import repeat from dw::core::Strings
---
{
"a": repeat("e", 0),
"b": repeat("e", 3),
"c": repeat("e", -2)
}
1
2
3
4
5
{
"a": "",
"b": "eee",
"c": ""
}
9.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.
Since Version: 2.2.0 ===== 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 the rightPad
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
import leftPad from dw::core::Strings
---
{
"a": rightPad(null, 3),
"b": rightPad("", 3),
"c": rightPad("bat", 5),
"d": rightPad("bat", 3),
"e": rightPad("bat", -1)
}
1
2
3
4
5
6
7
{
"a": null,
"b": " ",
"c": "bat ",
"d": "bat",
"e": "bat"
}
rightPad(Null, Number, String): Null
Helper function to make rightPad
work with null
value.
9.1.20. singularize
singularize(String): String
Converts a plural string to its singular form.
If the input is already singular (for example, "box"), the output will match the input.
Parameters
Name | Description |
---|---|
|
The string to convert to singular form. |
Example
This example converts the input string "boxes" to return "box".
1
2
3
4
5
%dw 2.0
import * from dw::core::Strings
output application/json
---
{ "singularize" : singularize("boxes") }
1
{ "singularize" : "box" }
singularize(Null): Null
Helper function that allows singularize to work with null values.
9.1.21. substringAfter
substringAfter(String, String): String
Gets the substring after the first occurrence of a separator. The separator is not returned.
Since Version: 2.2.0
Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. | `separator` | String to search for. |===
Example
This example shows how the substringAfter
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
import substringAfter from dw::core::Strings
---
{
"a": substringAfter(null, "'"),
"b": substringAfter("", "-"),
"c": substringAfter("abc", "b"),
"d": substringAfter("abcba", "b"),
"e": substringAfter("abc", "d"),
"f": substringAfter("abc", "")
}
1
2
3
4
5
6
7
8
9
{
"a": null,
"b": "",
"c": "c",
"d": "cba",
"e": "",
"f": "bc"
}
substringAfter(Null, String): Null
Helper function for substringAfter
work with null value.
9.1.22. substringAfterLast
substringAfterLast(String, String): String
Gets the substring after the last occurrence of a separator. The separator is not returned.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. | `separator` | String to search for. |===
Example
This example shows how the substringAfterLast
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
import substringAfterLast from dw::core::Strings
---
{
"a": substringAfterLast(null, "'"),
"b": substringAfterLast("", "-"),
"c": substringAfterLast("abc", "b"),
"d": substringAfterLast("abcba", "b"),
"e": substringAfterLast("abc", "d"),
"f": substringAfterLast("abc", "")
}
1
2
3
4
5
6
7
8
{
"a": null,
"b": "",
"c": "c",
"d": "a",
"e": "",
"f": null
}
substringAfterLast(Null, String): Null
Helper function for substringAfterLast
to work with null
value.
9.1.23. substringBefore
substringBefore(String, String): String
Gets the substring before the first occurrence of a separator. The separator is not returned.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. | `separator` | String to search for. |===
Example
This example shows how the substringBefore
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
import substringBefore from dw::core::Strings
---
{
"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
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
{
"a": null,
"b": "",
"c": "a",
"d": "ab",
"e": "",
"f": ""
}
----
==== substringBefore(Null, String): Null
Helper function for `substringBefore` to work with null value.
=== substringBeforeLast
==== substringBeforeLast(String, String): String
Gets the substring before the last occurrence of a separator. The separator is not returned.
*Since Version: 2.2.0*
===== Parameters
[%header, cols="1,3"]
|===
| Name | Description
| `text` | The input string.
| `separator` | String to search for.
|===
===== Example
This example shows how the `substringBeforeLast` behaves under different inputs and sizes.
====== Source
[source,DataWeave, linenums]
import substringBeforeLast from dw::core::Strings --- { "a": substringBeforeLast(null, "'"), "b": substringBeforeLast("", "-"), "c": substringBeforeLast("abc", "b"), "d": substringBeforeLast("abcba", "b"), "e": substringBeforeLast("abc", "d"), "f": substringBeforeLast("abc", "") }
====== Output [source,JSON,linenums]
{ "a": null, "b": "", "c": "ab", "d": "abc", "e": "", "f": "a" } ----
substringBeforeLast(Null, String): Null
Helper function for substringBeforeLast
to work with null value.
9.1.24. 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
{
"a" : underscore("customer"),
"b" : underscore("customer-first-name"),
"c" : underscore("customer NAME"),
"d" : underscore("customerName")
}
1
2
3
4
5
6
{
"a": "customer",
"b": "customer_first_name",
"c": "customer_name",
"d": "customer_name"
}
underscore(Null): Null
Helper function that allows underscore to work with null values.
9.1.25. unwrap
unwrap(String, String): String
Unwraps a given text
from a wrapper
text.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. | `wrapper` | the text used to unwrap |===
Example
This example shows how the unwrap
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import unwrap from dw::core::Strings
---
{
"a": unwrap(null, ""),
"b": unwrap(null, '\0'),
"c": unwrap("'abc'", "'"),
"d": unwrap("AABabcBAA", 'A'),
"e": unwrap("A", '#'),
"f": unwrap("#A", '#'),
"g": unwrap("A#", '#')
}
1
2
3
4
5
6
7
8
9
{
"a": null,
"b": null,
"c": "abc",
"d": "ABabcBA",
"e": "A",
"f": "A#",
"g": "#A"
}
unwrap(Null, String): Null
Helper function to make unwrap
work with null
value.
9.1.26. wrapIfMissing
wrapIfMissing(String, String): String
Wraps text
with wrapper
if that wrapper
is missing from the start or end of the given string.
Since Version: 2.2.0 ===== Parameters
[%header, cols="1,3"] |=== | Name | Description | `text` | The input string. | `wrapper` | The content used to wrap. |===
Example
This example shows how the wrapIfMissing
behaves under different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
import wrapIfMissing from dw::core::Strings
---
{
"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
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
{
"a": null,
"b": "'",
"c": "xabx",
"d": "'ab'",
"e": "/",
"f": "/a/b/c/",
"g": "/a/b/c/",
"h": "/a/b/c/"
}
----
==== wrapIfMissing(Null, String): Null
Helper function for `wrapIfMissing` to work with `null` value.
=== wrapWith
==== wrapWith(String, String): String
Wraps the specified `text` with the given `wrapper`
*Since Version: 2.2.0*
===== Parameters
[%header, cols="1,3"]
|===
| Name | Description
| `text` | The input string.
| `wrapper` | The content used to wrap.
|===
===== Example
This example shows how the `wrapWith` behaves under different inputs and sizes.
====== Source
[source,DataWeave, linenums]
import wrapWith from dw::core::Strings --- { "a": wrapWith(null, "'"), "b": wrapWith("", "'"), "c": wrapWith("ab", "x"), "d": wrapWith("'ab'", "'"), "e": wrapWith("ab", "'") }
====== Output [source,JSON,linenums]
{ "e": "'ab'", "a": null, "b": "''", "c": "xabx", "d": "''ab''" } ----
wrapWith(Null, String): Null
Helper function for wrapWith
to work with null value.
10. 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.
10.1. Functions
10.1.1. compose
compose(Array<String>, Array<String>): String
Uses a custom interpolator to replace URL components with a
encodeURIComponent
result.
Parameters
Name | Description |
---|---|
|
A string array that provides the part of the URL to encode. |
Example
This example passes in text to encode using $(myText)
, where myText
is a variable defined in the header. Notice that the spaces in the input are
encoded in the output URL as %20
. Also notice that the entire input to the
compose
function is surrounded by backticks.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::URL
var myText = " text to encode "
output application/json
---
{ "composition" : compose `http://asd/$(myText)/text` }
1
{ "composition": "http://asd/%20text%20to%20encode%20/text" }
10.1.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
{
"decodeURI" : decodeURI('http://asd/%20text%20to%20decode%20/text')
}
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
{
"decodeURI": "http://asd/ text to decode /text"
}
=== decodeURIComponent
==== decodeURIComponent(String): String
Decodes a Uniform Resource Identifier (URI) component previously created
by `encodeURIComponent` or a similar routine.
For an example, see `encodeURIComponent`.
===== Parameters
[%header, cols="1,3"]
|===
| Name | Description
| `text` | URI component string.
|===
===== Example
This example decodes a variety of URI components.
====== Source
[source,DataWeave, linenums]
%dw 2.0 import * from dw::core::URL output application/json --- { "decodeURIComponent": { "decodeURIComponent" : decodeURIComponent("%20PATH/%20TO%20/DECODE%20"), "decodeURIComponent" : decodeURIComponent("%3B%2C%2F%3F%3A%40%26%3D"), "decodeURIComponent" : decodeURIComponent("%2D%5F%2E%21%7E%2A%27%28%29%24"), } }
====== Output [source,JSON,linenums]
{ decodeURIComponent: { decodeURIComponent: " PATH/ TO /DECODE ", decodeURIComponent: ";,/?:@&=", decodeURIComponent: "-_.!~*'()\$" } }
=== encodeURI ==== encodeURI(String): String Encodes a URI with UTF-8 escape sequences. Applies up to four escape sequences for characters composed of two "surrogate" characters. The function assumes that the URI is a complete URI, so it does not encode reserved characters that have special meaning. The function _does not encode these characters_ with UTF-8 escape sequences: [%header, cols="2,2"] |=== | Type (not escaped) | Examples | Reserved characters | ; , / ? : @ & = $ | Unescaped characters | alphabetic, decimal digits, - _ . ! ~ * ' ( ) | Number sign | # |=== ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `text` | The URI to encode. |=== ===== Example This example shows encodes spaces in one URL and lists some characters that do not get encoded in the `not_encoded` string. ====== Source [source,DataWeave, linenums]
{ "encodeURI" : encodeURI("http://asd/ text to decode /text"), "not_encoded": encodeURI("http://:;,/?:@&=\$-.!~*'()") }
====== Output [source,JSON,linenums]
{ "encodeURI": "http://asd/%20text%20to%20decode%20/%25/\"\'/text", "not_encoded": "http://:;,/?:@&=$-.!~*'()" }
=== encodeURIComponent ==== encodeURIComponent(String): String Escapes certain characters in a URI component using UTF-8 encoding. There can be only four escape sequences for characters composed of two "surrogate" * characters. `encodeURIComponent` escapes all characters _except the following_: alphabetic, decimal digits, `- _ . ! ~ * ' ( )`. Note that `encodeURIComponent` differs from `encodeURI` in that it encodes reserved characters and the Number sign `#` of `encodeURI`: [%header, cols="2,2"] |=== | Type | Includes | Reserved characters | | Unescaped characters | alphabetic, decimal digits, - _ . ! ~ * ' ( ) | Number sign | |=== ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `text` | URI component string. |=== ===== Example This example encodes a variety of URI components. ====== Source [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::URL output application/json --- { "comparing_encode_functions_output" : { "encodeURIComponent" : encodeURI(" PATH/ TO /ENCODE "), "encodeURI" : encodeURI(" PATH/ TO /ENCODE "), "encodeURIComponent_to_hex" : encodeURIComponent(";,/?:@&="), "encodeURI_not_to_hex" : encodeURI(";,/?:@&="), "encodeURIComponent_not_encoded" : encodeURIComponent("-.!~'()"), "encodeURI_not_encoded" : encodeURI("-.!~'()") } }
====== Output [source,JSON,linenums]
{ "comparing_encode_functions_output": { "encodeURIComponent": "%20PATH/%20TO%20/ENCODE%20", "encodeURI": "%20PATH/%20TO%20/ENCODE%20", "encodeURIComponent_to_hex": "%3B%2C%2F%3F%3A%40%26%3D", "encodeURI_not_to_hex": ";,/?:@&=", "encodeURIComponent_not_encoded": "-.!~'()", "encodeURI_not_encoded": "-.!~'()" } }
=== parseURI ==== parseURI(String): URI Parses a URL and returns a `URI` object. The `isValid: Boolean` property in the output `URI` object indicates whether the parsing process succeeded. Every field in this object is optional, and a field will appear in the output only if it was present in the URL input. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `uri` | The URI input. |=== ===== Example This example parses a URL. ====== Source [source,DataWeave, linenums]
%dw 2.0 import * from dw::core::URL output application/json --- { 'composition': parseURI('https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#footer') }
====== Output [source,JSON,linenums]
{ "composition": { "isValid": true, "raw": "https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#footer", "host": "en.wikipedia.org", "authority": "en.wikipedia.org", "fragment": "footer", "path": "/wiki/Uniform_Resource_Identifier", "scheme": "https", "isAbsolute": true, "isOpaque": false } }
== Types === URI .Definition [source,DataWeave,linenums]
{ isValid: Boolean, host?: String, authority?: String, fragment?: String, path?: String, port?: Number, query?: String, scheme?: String, user?: String, isAbsolute?: Boolean, isOpaque?: Boolean }
= dw::extension::DataFormat This module contains the require stuff for registering a new Data Format on the language == Types === DataFormat .Definition [source,DataWeave,linenums]
{ / * True if this is data format is represented in a binary representation instead of text, if not present is false / binaryFormat?: Boolean, / * The default charset of this format if any / defaultCharset?: String, / * Returns the list of file extensions with the . (".json", ".xml", etc…) that should be assigned to this Data Format / fileExtensions?: Array<String>, / * The list of MimeTypes that are accepted / acceptedMimeTypes: Array<MimeType>, / * This function will be in charge of reading the raw content and transform it into the DW canonical model / reader: (content: Binary, charset: String, settings: ReaderSettings) → Any, / * This function will be in charge of writing the DW canonical model into Binary content / writer: (value: Any, settings: WriterSettings) → Binary }
=== EmptySettings .Definition [source,DataWeave,linenums]
Object
=== EncodingSettings .Definition [source,DataWeave,linenums]
{ / * Encoding to be used by this writer. / encoding?: String }
=== MimeType .Definition [source,DataWeave,linenums]
String
=== Settings .Definition [source,DataWeave,linenums]
Object
== Annotations = dw::module::Multipart This helper module provide functions for creating MultiPart and formats and parts (including fields and boundaries) of MultiPart formats. To use this module, you must import it into your DataWeave code, for example, by adding the line `import dw::module::Multipart` to the header of your DataWeave script. == Functions === field ==== field({| name: String, value: Any, mime?: String, fileName?: String |}): MultipartPart Creates a `MultipartPart` data structure using the specified part name, input content for the part, format (or mime type), and optionally, file name. This version of the `field` function accepts arguments as an array of objects that use the parameter names as keys, for example: `Multipart::field({name:"order",value: myOrder, mime: "application/json", fileName: "order.json"})` ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `opts` a| Array of objects that specifies: * A unique `name` (required) for the `Content-Disposition` header of the part. * A `value` (required) for the content of the part. * `mime` (optional for strings) for the mime type (for example, `application/json`) to apply to content within the part. This setting can be used to transform the input type, for example, from JSON to XML. * An optional `fileName` value that you can supply to the `filename` parameter in the part's `Content-Disposition` header. |=== ===== Example This example produces two parts. The first part (named `order`) outputs content in JSON and provides a file name for the part (`order.json`). The second (named `clients`) outputs content in XML and does not provide a file name. Also notice that in this example you need to add the function's namespace to the function name, for example, `Multipart::field`. ====== Source [source,DataWeave,linenums]
%dw 2.0 import dw::module::Multipart output multipart/form-data var myOrder = [ { order: 1, amount: 2 }, { order: 32, amount: 1 } ] var myClients = { clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } } } --- { parts: { order: Multipart::field({name:"order",value: myOrder, mime: "application/json", fileName: "order.json"}), clients: Multipart::field({name:"clients", value: myClients, mime: "application/xml"}) } }
====== Output [source,txt,linenums]
------=_Part_8032_681891620.1542560124825 Content-Type: application/json Content-Disposition: form-data; name="order"; filename="order.json"
[ { "order": 1, "amount": 2 }, { "order": 32, "amount": 1 } ] ------=_Part_8032_681891620.1542560124825 Content-Type: application/xml Content-Disposition: form-data; name="clients"
<clients> <client> <id>1</id> <name>Mariano</name> </client> <client> <id>2</id> <name>Shoki</name> </client> </clients> ------=_Part_8032_681891620.1542560124825--
==== field(String, Any, String, String): MultipartPart Creates a `MultipartPart` data structure using the specified part name, input content for the part, format (or mime type), and optionally, file name. This version of the `field` function accepts arguments in a comma-separated list, for example: [source,txt,linenums]
Multipart::field("order", myOrder,"application/json", "order.json")`
===== Parameters [%header, cols="1,3"] |=== | Name | Description | `opts` a| A set of parameters that specify: * A unique `name` (required) for the `Content-Disposition` header of the part. * A `value` (required) for the content of the part. * `mime` (optional for strings) for the mime type (for example, `application/json`) to apply to content within the part. This type can be used to transform the input type. * An optional `fileName` value that you can supply to the `filename` parameter in the part's `Content-Disposition` header. |=== ===== Example This example produces two parts. The first part (named `order`) outputs content in JSON and provides a file name for the part (`order.json`). The second (named `clients`) outputs content in XML and does not provide a file name. The only difference between this `field` example and the previous `field` example is the way you pass in arguments to the method. Also notice that in this example you need to add the function's namespace to the function name, for example, `Multipart::field`. ====== Source [source,DataWeave,linenums]
%dw 2.0 import dw::module::Multipart output multipart/form-data var myOrder = [ { order: 1, amount: 2 }, { order: 32, amount: 1 } ] var myClients = { clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } } } --- { parts: { order: Multipart::field("order", myOrder, "application/json", "order.json"), clients: Multipart::field("clients", myClients, "application/xml") } }
====== Output [source,txt,linenums]
------=_Part_4846_2022598837.1542560230901 Content-Type: application/json Content-Disposition: form-data; name="order"; filename="order.json"
[ { "order": 1, "amount": 2 }, { "order": 32, "amount": 1 } ] ------=_Part_4846_2022598837.1542560230901 Content-Type: application/xml Content-Disposition: form-data; name="clients"
<clients> <client> <id>1</id> <name>Mariano</name> </client> <client> <id>2</id> <name>Shoki</name> </client> </clients> ------=_Part_4846_2022598837.1542560230901--
=== file ==== file({| name: String, path: String, mime?: String, fileName?: String |}) Creates a `MultipartPart` data structure from a resource file. This version of the `file` function accepts arguments as an array of objects that use the parameter names as keys, for example: [source,txt,linenums]
Multipart::file({ name: "myFile", path: "myClients.json", mime: "application/json", fileName: "partMyClients.json"})
===== Parameters [%header, cols="1,3"] |=== | Name | Description | `opts` a| Array of objects that specifies: * A unique `name` (required) for the `Content-Disposition` header of the part. * A `path` (required) relative to the `src/main/resources` project path for the Mule app. * `mime` (optional for strings) for the mime type (for example, `application/json`) to apply to content within the part. This setting _cannot_ be used to transform the input mime type. * An optional `fileName` value for the `filename` parameter in the part's `Content-Disposition` header. Defaults to the string `"filename"` if not supplied. This value does not need to match the input file name. |=== ===== Example This example inserts file content from a `MultipartPart` into a `Multipart` data structure. It uses the `form` function to create the `Multipart` and uses `file` to create a part named `myClient` with JSON content from an external file `myClients.json`. It also specifies `partMyClients.json` as the value for to the `filename` parameter. ====== Source [source,DataWeave,linenums]
%dw 2.0 import dw::module::Multipart output multipart/form-data var myClients = "myClients.json" var myArgs = { name: "myFile", path: "myClients.json", mime: "application/json", * fileName: "partMyClients.json"} --- Multipart::form([ Multipart::file(myArgs) ])
====== Input A file called `myClients.json` and located in `src/main/resources` with the following content. [source,JSON,linenums]
clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } }
====== Output [source,json,linenums]
------=_Part_1586_1887987980.1542569342438 Content-Type: application/json Content-Disposition: form-data; name="myFile"; filename="partMyClients.json"
{ clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } } } ------=_Part_1586_1887987980.1542569342438--
==== file(String, String, String, String) Creates a `MultipartPart` data structure from a resource file. This version of the `file` function accepts arguments in a comma-separated list, for example: [source,txt,linenums]
Multipart::field("myFile", myClients, 'application/json', "partMyClients.json")
===== Parameters [%header, cols="1,3"] |=== | Name | Description | `opts` a| Array of objects that specifies: * A unique `name` (required) for the `Content-Disposition` header of the part. * A `path` (required) relative to the `src/main/resources` project path for the Mule app. * `mime` (optional for strings) for the mime type (for example, `application/json`) to apply to content within the part. This setting _cannot_ be used to transform the input mime type. * An optional `fileName` value for the `filename` parameter in the part's `Content-Disposition` header. Defaults to the string `"filename"` if not supplied. This value does not need to match the input file name. |=== ===== Example This example inserts file content from a `MultipartPart` into a `Multipart` data structure. It uses the `form` function to create the `Multipart` type and uses `file` to create a part named `myClient` with JSON content from an external file `myClients.json`. It also specifies `partMyClients.json` as the value for to the `filename` parameter. ====== Source [source,DataWeave,linenums]
%dw 2.0 import dw::module::Multipart var myClients = "myClients.json" output multipart/form-data --- Multipart::form([ Multipart::file("myFile", myClients, 'application/json', "partMyClients.json") ])
====== Input A file called `myClients.json` and located in `src/main/resources` with the following content. [source,JSON,linenums]
clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } }
====== Output [source,json,linenums]
------=_Part_1586_1887987980.1542569342438 Content-Type: application/json Content-Disposition: form-data; name="myFile"; filename="partMyClients.json"
{ clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } } } ------=_Part_1586_1887987980.1542569342438--
=== form ==== form(Array<MultipartPart>): Multipart Creates a `Multipart` data structure using a specified array of parts. ===== Parameters [%header, cols="1,3"] |=== | Name | Description | `parts` | An array of parts (`MultipartPart` data structures). |=== ===== Example This example creates a `Multipart` data structure that contains parts, which are described in examples for the `field` function. For additional uses of `form`, see examples in the Multipart `file` and `field` documentation. ====== Source [source,DataWeave,linenums]
%dw 2.0 import dw::module::Multipart output multipart/form-data var firstPart = "content for my first part" var secondPart = "content for my second part" --- { parts: { part1: Multipart::field({name:"myFirstPart",value: firstPart}), part2: Multipart::field("mySecondPart", secondPart) } }
====== Output [source,json,linenums]
------=_Part_320_1528378161.1542639222352 Content-Disposition: form-data; name="myFirstPart"
content for my first part ------=_Part_320_1528378161.1542639222352 Content-Disposition: form-data; name="mySecondPart"
content for my second part ------=_Part_320_1528378161.1542639222352--
10.1.3. generateBoundary
generateBoundary(Number): String
Helper function for generating boundaries in Multipart
data structures.
10.2. Types
10.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 } }
10.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 }
11. 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.
11.1. Functions
11.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: []
}
}
11.2. Types
11.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> }
11.2.2. Difference
Describes a single difference between two values at a given structure.
1
{ expected: String, actual: String, path: String }
12. 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.
12.1. Functions
12.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 }
12.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"
}
12.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"
}
]
}
12.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 }
12.2. Types
12.2.1. DurationMeasurement
A return type that contains the execution time and result of a function call.
1
{ time: Number, result: T }
12.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 }