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. ++
++<S, T>(source: Array<S>, with: 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 |
---|---|
source |
The source array. |
with |
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}] }
++(source: String, with: 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 |
---|---|
source |
The source string. |
with |
The string to concatenate with the source string. |
Example
This example concatenates two strings. Here, Mule
is treated as
Array<String> ["M", "u", "l", "e"]
. Notice that the example outputs the
result MuleSoft
as the value of a JSON object.
1
2
3
4
%dw 2.0
output application/json
---
{ "name" : "Mule" ++ "Soft" }
1
{ "name": "MuleSoft" }
++<T <: Object, Q <: Object>(source: T, with: Q): T & Q
Concatenates two objects and returns one flattened object.
The ++
operator extracts all the key-values pairs from each object,
then combines them together into one result object.
Parameters
Name | Description |
---|---|
source |
The source object. |
with |
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: Date, time: 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 |
---|---|
date |
A |
time |
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" }
++(time: LocalTime, date: Date): LocalDateTime
Appends a LocalTime
with a Date
to return a LocalDateTime
.
Note that the order in which the two objects are concatenated is irrelevant,
so logically, LocalTime Date` produces the same result as
`Date LocalTime
.
Parameters
Name | Description |
---|---|
time |
A |
date |
A |
Example
This example concatenates LocalTime
and Date
objects to return a
LocalDateTime
.
1
2
3
4
%dw 2.0
output application/json
---
{ "LocalDateTime" : (|23:57:59| ++ |2003-10-01|) }
1
{ "LocalDateTime": "2017-10-01T23:57:59" }
++(date: Date, time: 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 |
---|---|
date |
A |
time |
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: Time, date: 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 |
---|---|
time |
A |
date |
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: Date, timezone: TimeZone): DateTime
Appends a TimeZone
to a Date
type value and returns a DateTime
result.
Parameters
Name | Description |
---|---|
date |
A |
timezone |
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: TimeZone, date: Date): DateTime
Appends a Date
to a TimeZone
in order to return a DateTime
.
Parameters
Name | Description |
---|---|
date |
A |
timezone |
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" }
++(dateTime: LocalDateTime, timezone: TimeZone): DateTime
Appends a TimeZone
to a LocalDateTime
in order to return a DateTime
.
Parameters
Name | Description |
---|---|
dateTime |
A |
timezone |
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: TimeZone, datetime: LocalDateTime): DateTime
Appends a LocalDateTime
to a TimeZone
in order to return a DateTime
.
Parameters
Name | Description |
---|---|
dateTime |
A |
timezone |
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" }
++(time: LocalTime, timezone: TimeZone): Time
Appends a TimeZone
to a LocalTime
in order to return a Time
.
Parameters
Name | Description |
---|---|
time |
A |
timezone |
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: TimeZone, time: LocalTime): Time
Appends a LocalTime
to a TimeZone
in order to return a Time
.
Parameters
Name | Description |
---|---|
time |
A |
timezone |
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. —
--<S>(source: Array<S>, toRemove: Array<Any>): Array<S>
Removes specified values from an input value.
This version of --
removes all instances of the 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 |
---|---|
source |
The array containing items to remove. |
toRemove |
Items to remove from the source array. |
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>(source: { (K)?: V }, toRemove: Object): { (K)?: V }
Removes specified key-value pairs from an object.
Parameters
Name | Description |
---|---|
source |
The source object (an |
toRemove |
Object that contains the key-value pairs 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" }
--(source: Object, keys: Array<String>)
Removes all key-value pairs from the source object that match the specified search key.
Parameters
Name | Description |
---|---|
source |
The source object (an |
toRemove |
An array of keys to specify 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" }
--(source: Object, keys: Array<Key>)
Removes specified key-value pairs from an object.
Parameters
Name | Description |
---|---|
source |
The source object (an |
keys |
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" }
--(source: Null, keys: Any)
Helper function that enables --
to work with a null
value.
1.1.3. abs
abs(number: Number): Number
Returns the absolute value of a number.
Parameters
Name | Description |
---|---|
number |
The number to evaluate. |
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(values: Array<Number>): Number
Returns the average of numbers listed in an array.
An array that is empty or that contains a non-numeric value results in an error.
Parameters
Name | Description |
---|---|
values |
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): Number
Rounds a number up to the nearest whole number.
Parameters
Name | Description |
---|---|
number |
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<T>(@StreamCapable items: Array<T>, element: 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 |
---|---|
items |
The input array. |
elements |
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(text: String, toSearch: String): Boolean
Indicates whether a string contains a given substring. Returns true
or false
.
Parameters
Name | Description |
---|---|
text |
An input string (a |
toSearch |
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(text: String, matcher: Regex): Boolean
Returns true
if a string contains a match to a regular expression, false
if not.
Parameters
Name | Description |
---|---|
text |
An input string. |
matcher |
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 }
contains(text: Null, matcher: Any): false
Helper function that enables contains
to work with a null
value.
1.1.7. daysBetween
daysBetween(from: Date, to: Date): Number
Returns the number of days between two dates.
Parameters
Name | Description |
---|---|
from |
From date (a |
to |
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<T>(@StreamCapable items: Array<T>, criteria: (item: T, index: Number) -> Any): Array<T>
Iterates over the input and returns the unique elements in it.
DataWeave uses the result of the provided lambda as the uniqueness criteria.
This version of distinctBy
finds unique values in an array. Other versions
act on an object and handle a null
value.
Parameters
Name | Description |
---|---|
items |
The array to evaluate. |
criteria |
The criteria used to select an |
Example
This example inputs an array that contains duplicate numbers and returns an
array with unique numbers from that input. Note that you can write the same
expression using an anonymous parameter for the values:
[0, 1, 2, 3, 3, 2, 1, 4] distinctBy $
1
2
3
4
%dw 2.0
output application/json
---
[0, 1, 2, 3, 3, 2, 1, 4] distinctBy (value) -> { "unique" : value }
1
[ 0, 1, 2, 3, 4]
Example
This example removes duplicates of "Kurt Cagle"
from an array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
%dw 2.0
output application/json
var record = {
"title": "XQuery Kick Start",
"author": [
"James McGovern",
"Per Bothner",
"Kurt Cagle",
"James Linn",
"Kurt Cagle",
"Kurt Cagle",
"Kurt Cagle",
"Vaidyanathan Nagarajan"
],
"year":"2000"
}
---
{
"book" : {
"title" : record.title,
"year" : record.year,
"authors" : record.author distinctBy $
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"book": {
"title": "XQuery Kick Start",
"year": "2000",
"authors": [
"James McGovern",
"Per Bothner",
"Kurt Cagle",
"James Linn",
"Vaidyanathan Nagarajan"
]
}
}
distinctBy<K, V>(object: { (K)?: V }, criteria: (value: V, key: K) -> Any): Object
Removes duplicate key-value pairs from an object.
Parameters
Name | Description |
---|---|
object |
The object from which to remove the key-value pairs. |
criteria |
The |
Example
This example inputs an object that contains duplicate key-value pairs and
returns an object with key-value pairs from that input. Notice that the
keys (a
and A
) are not treated with case sensitivity, but the values
(b
and B
) are. Also note that you can write the same expression using
an anonymous parameter for the values:
{a : "b", a : "b", A : "b", a : "B"} distinctBy $
1
2
3
4
%dw 2.0
output application/json
---
{a : "b", a : "b", A : "b", a : "B"} distinctBy (value) -> { "unique" : value }
1
{ "a": "b", "a": "B" }
Example
This example removes duplicates (<author>James McGovern</author>
)
from <book/>
.
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/xml
---
{
book : {
title : payload.book.title,
authors: payload.book.&author distinctBy $
}
}
1
2
3
4
5
6
7
8
<book>
<title> "XQuery Kick Start"</title>
<author>James Linn</author>
<author>Per Bothner</author>
<author>James McGovern</author>
<author>James McGovern</author>
<author>James McGovern</author>
</book>
1
2
3
4
5
6
7
8
<book>
<title> "XQuery Kick Start"</title>
<authors>
<author>James Linn</author>
<author>Per Bothner</author>
<author>James McGovern</author>
</authors>
</book>
distinctBy(@StreamCapable items: Null, criteria: (item: Nothing, index: Nothing) -> Any): Null
Helper function that enables distinctBy
to work with a null
value.
1.1.9. endsWith
endsWith(text: String, suffix: String): Boolean
Returns true
if a string ends with a provided substring, false
if not.
Parameters
Name | Description |
---|---|
text |
The input string (a |
suffix |
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 ]
endsWith(text: Null, suffix: Any): false
Helper function that enables endsWith
to work with a null
value.
1.1.10. entriesOf
entriesOf<T <: Object>(obj: T): Array<{| key: Key, value: Any, attributes: Object |}>
Returns an array of key-value pairs that describe the key, value, and any attributes in the input object.
Parameters
Name | Description |
---|---|
obj |
The object to describe. |
Example
This example returns the key, value, and attributes from the object specified
in the variable myVar
. The object is the XML input to the read
function.
1
2
3
4
5
%dw 2.0
var myVar = read('<xml attr="x"><a>true</a><b>1</b></xml>', 'application/xml')
output application/json
---
{ "entriesOf" : entriesOf(myVar) }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"entriesOf": [
{
"key": "xml",
"value": {
"a": "true",
"b": "1"
},
"attributes": {
"attr": "x"
}
}
]
}
entriesOf(obj: Null): Null
Helper function that enables entriesOf
to work with a null
value.
1.1.11. evaluateCompatibilityFlag
evaluateCompatibilityFlag(flag: String): Boolean
Returns the value of the compatibility flag with the specified name.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The name of the compatibility flag to evaluate. |
Example
This example gets the com.mulesoft.dw.xml_reader.honourMixedContentStructure
compatibility flag value in the current
the DataWeave version.
1
2
3
4
5
6
%dw 2.0
output application/json
---
{
"com.mulesoft.dw.xml_reader.honourMixedContentStructure": evaluateCompatibilityFlag("com.mulesoft.dw.xml_reader.honourMixedContentStructure")
}
1
2
3
{
"com.mulesoft.dw.xml_reader.honourMixedContentStructure": true
}
1.1.12. filter
filter<T>(@StreamCapable items: Array<T>, criteria: (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 |
---|---|
items |
The array to filter. |
criteria |
Boolean expression that selects an |
Example
This example returns an array of values in the array that are greater than 2
.
1
[9,2,3,4,5] filter (value, index) -> (value > 2)
1
[9,3,4,5]
Example
This example returns an array of all the users with age bigger or equal to 30. The script accesses data of each element from within the lambda expression.
1
2
3
4
%dw 2.0
---
[{name: "Mariano", age: 37}, {name: "Shoki", age: 30}, {name: "Tomo", age: 25}, {name: "Ana", age: 29}]
filter ((value, index) -> value.age >= 30)
1
2
3
4
5
6
7
8
9
10
[
{
"name": "Mariano",
"age": 37
},
{
"name": "Shoki",
"age": 30
}
]
Example
This example returns an array of all items found at an index ($$
)
greater than 1
where the value of the element is less than 5
. Notice that
it is using anonymous parameters as selectors instead of using named
parameters in an anonymous function.
1
2
3
4
%dw 2.0
output application/json
---
[9, 2, 3, 4, 5] filter (($$ > 1) and ($ < 5))
1
[3,4]
Example
This example reads a JSON array that contains objects with user
and error
keys, and uses the filter
function to return only the objects in which the value of the error
key is null
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
%dw 2.0
output application/json
var users = [
{
"user": {
"name": "123",
"lastName": "Smith"
},
"error": "That name doesn't exists"
},
{
"user": {
"name": "John",
"lastName": "Johnson"
},
"error": null
}
]
---
users filter ((item, index) -> item.error == null)
1
2
3
4
5
6
7
8
9
[
{
"user": {
"name": "John",
"lastName": "Johnson"
},
"error": null
}
]
filter(@StreamCapable text: String, criteria: (character: String, index: Number) -> Boolean): String
Iterates over a string and applies an expression that returns matching values.
The expression must return true
or false
. If the expression returns true
for a character or index in the array, the character gets captured in the output string.
If it returns false
for a character or index in the array, that character gets
filtered out of the output. If there are no matches, the output string will
be empty.
Parameters
Name | Description |
---|---|
text |
The text to filter. |
criteria |
The criteria to use. |
Example
This example shows how filter
can be used to remove all characters in odd positions.
1
2
3
4
%dw 2.0
output application/json
---
"hello world" filter ($$ mod 2) == 0
1
"hlowrd"
filter(@StreamCapable value: Null, criteria: (item: Nothing, index: Nothing) -> Any): Null
Helper function that enables filter
to work with a null
value.
1.1.13. filterObject
filterObject<K, V>(@StreamCapable value: { (K)?: V }, criteria: (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 |
---|---|
value |
The source object to evaluate. |
criteria |
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" }
Example
This example outputs an object that contains only the values that are not null
in the input JSON object.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
var myObject = {
str1 : "String 1",
str2 : "String 2",
str3 : null,
str4 : "String 4",
}
---
myObject filterObject $ != null
1
2
3
4
5
{
"str1": "String 1",
"str2": "String 2",
"str4": "String 4"
}
filterObject(value: Null, criteria: (value: Nothing, key: Nothing, index: Nothing) -> Any): Null
Helper function that enables filterObject
to work with a null
value.
1.1.14. find
find<T>(@StreamCapable() elements: Array<T>, elementToFind: 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 |
---|---|
elements |
An array with elements of any type. |
elementToFind |
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(@StreamCapable() text: String, matcher: 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 |
---|---|
text |
A string. |
matcher |
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(@StreamCapable() text: String, textToFind: String): Array<Number>
Lists indices where the specified characters of a string are present.
Parameters
Name | Description |
---|---|
text |
A source string. |
textToFind |
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]
find(@StreamCapable() text: Null, textToFind: Any): Array<Nothing>
Helper function that enables find
to work with a null
value.
1.1.15. flatMap
flatMap<T, R>(@StreamCapable items: Array<T>, mapper: (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 |
---|---|
items |
The array to map. |
mapper |
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<T, R>(@StreamCapable value: Null, mapper: (item: Nothing, index: Nothing) -> Any): Null
Helper function that enables flatMap
to work with a null
value.
1.1.16. flatten
flatten<T, Q>(@StreamCapable items: Array<Array<T> | Q>): Array<T | Q>
Turns a set of subarrays (such as [ [1,2,3], [4,5,[6]], [], [null] ]
) into a single, flattened array (such as [ 1, 2, 3, 4, 5, [6], null ]
).
Note that it flattens only the first level of subarrays and omits empty subarrays.
Parameters
Name | Description |
---|---|
items |
The input array of arrays made up of any supported types. |
Example
This example defines three arrays of numbers, creates another array containing those three arrays, and then uses the flatten function to convert the array of arrays into a single array with all values.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
var array1 = [1,2,3]
var array2 = [4,5,6]
var array3 = [7,8,9]
var arrayOfArrays = [array1, array2, array3]
---
flatten(arrayOfArrays)
1
[ 1,2,3,4,5,6,7,8,9 ]
Example
This example returns a single array from nested arrays of objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
%dw 2.0
var myData =
{ user : [
{
group : "dev",
myarray : [
{ name : "Shoki", id : 5678 },
{ name : "Mariano", id : 9123 }
]
},
{
group : "test",
myarray : [
{ name : "Sai", id : 2001 },
{ name : "Peter", id : 2002 }
]
}
]
}
output application/json
---
flatten(myData.user.myarray)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[
{
"name": "Shoki",
"id": 5678
},
{
"name": "Mariano",
"id": 9123
},
{
"name": "Sai",
"id": 2001
},
{
"name": "Peter",
"id": 2002
}
]
Note that
if you use myData.user.myarray
to select the array of objects in myarray
,
instead of using flatten(myData.user.myarray)
, the output is a nested array of objects:
1
2
3
4
5
6
7
8
9
10
11
12
[
[
{
"name": "Shoki",
"id": 5678
},
{
"name": "Mariano",
"id": 9123
}
]
]
flatten(@StreamCapable value: Null): Null
Helper function that enables flatten
to work with a null
value.
1.1.17. floor
floor(number: Number): Number
Rounds a number down to the nearest whole number.
Parameters
Name | Description |
---|---|
number |
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.18. groupBy
groupBy<T, R>(items: Array<T>, criteria: (item: T, index: Number) -> R): {| (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 |
---|---|
items |
The array to group. |
criteria |
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<R>(text: String, criteria: (character: String, index: Number) -> R): { (R): String }
Returns an object that groups characters from a string 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 |
---|---|
text |
The string to group by. |
criteria |
The criteria to use. |
Example
This example shows howyou can use groupBy
to split a string into
vowels and not vowels.
1
2
3
4
%dw 2.0
output application/json
---
"hello world!" groupBy (not isEmpty($ find /[aeiou]/))
1
2
3
4
{
"false": "hll wrld!",
"true": "eoo"
}
groupBy<K, V, R>(object: { (K)?: V }, criteria: (value: V, key: K) -> R): { (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 |
---|---|
object |
The object containing objects to group. |
criteria |
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(value: Null, criteria: (Nothing, Nothing) -> Any): Null
Helper function that enables groupBy
to work with a null
value.
1.1.19. indexOf
indexOf(array: Array, value: Any): Number
Returns the index of the first occurrence of the specified element in this array, or -1
if this list does not contain the element.
Parameters
Name | Description |
---|---|
array |
The array of elements to search. |
value |
The value to search. |
Example
This example shows how indexOf
behaves given different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
present: ["a","b","c","d"] indexOf "c",
notPresent: ["x","w","x"] indexOf "c",
presentMoreThanOnce: ["a","b","c","c"] indexOf "c",
}
1
2
3
4
5
{
"present": 2,
"notPresent": -1,
"presentMoreThanOnce": 2
}
indexOf(theString: String, search: String): Number
Returns the index of the first occurrence of the specified String in this String.
Parameters
Name | Description |
---|---|
theString |
The string to search. |
search |
The string to find within |
Example
This example shows how the indexOf
behaves under different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
present: "abcd" indexOf "c",
notPresent: "xyz" indexOf "c",
presentMoreThanOnce: "abcdc" indexOf "c",
}
1
2
3
4
5
{
"present": 2,
"notPresent": -1,
"presentMoreThanOnce": 2
}
indexOf(array: Null, value: Any): Number
Helper method to make indexOf null friendly
1.1.20. isBlank
isBlank(text: String | Null): Boolean
Returns true
if the given string is empty (""
), completely composed of whitespaces, or null
. Otherwise, the function returns false
.
Parameters
Name | Description |
---|---|
text |
An input string to evaluate. |
Example
This example indicates whether the given values are blank. It also uses the not
and !
operators to check that a value is not blank.
The !
operator is supported starting in Dataweave 2.2.0. Use !
only in Mule 4.2 and later versions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
%dw 2.0
output application/json
var someString = "something"
var nullString = null
---
{
// checking if the string is blank
"emptyString" : isBlank(""),
"stringWithSpaces" : isBlank(" "),
"textString" : isBlank(someString),
"somePayloadValue" : isBlank(payload.nonExistingValue),
"nullString" : isBlank(nullString),
// checking if the string is not blank
"notEmptyTextString" : not isBlank(" 1234"),
"notEmptyTextStringTwo" : ! isBlank("")
}
1
2
3
4
5
6
7
8
9
{
"emptyString": true,
"stringWithSpaces": true,
"textString": false,
"somePayloadValue": true,
"nullString": true,
"notEmptyTextString": true,
"notEmptyTextStringTwo": false
}
1.1.21. isDecimal
isDecimal(number: Number): Boolean
Returns true
if the given number contains a decimal, false
if not.
Parameters
Name | Description |
---|---|
number |
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.22. isEmpty
isEmpty(elements: 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 |
---|---|
elements |
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(value: String): Boolean
Returns true
if the input string is empty, false
if not.
Parameters
Name | Description |
---|---|
value |
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(value: Object): Boolean
Returns true
if the given object is empty, false
if not.
Parameters
Name | Description |
---|---|
value |
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 ]
isEmpty(value: Null): true
Returns true
if the input is null
.
Parameters
Name | Description |
---|---|
value |
|
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 }
1.1.23. isEven
isEven(number: Number): Boolean
Returns true
if the number or numeric result of a mathematical operation is
even, false
if not.
Parameters
Name | Description |
---|---|
number |
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.24. isInteger
isInteger(number: Number): Boolean
Returns true
if the given number is an integer (which lacks decimals),
false
if not.
Parameters
Name | Description |
---|---|
number |
The number to evaluate. |
Example
This example indicates whether the input is an integer for different values. Note numbers within strings get coerced to numbers.
1
2
3
4
%dw 2.0
output application/json
---
[isInteger(1), isInteger(2.0), isInteger(2.2), isInteger("1")]
1
[ true, true, false, true ]
1.1.25. isLeapYear
isLeapYear(dateTime: 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 |
---|---|
dateTime |
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: Date): Boolean
Returns true
if the input Date
is a leap year, 'false' if not.
Parameters
Name | Description |
---|---|
date |
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(datetime: LocalDateTime): Boolean
Returns true
if the input local date-time is a leap year, 'false' if not.
Parameters
Name | Description |
---|---|
datetime |
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.26. isOdd
isOdd(number: Number): Boolean
Returns true
if the number or numeric result of a mathematical operation is
odd, false
if not.
Parameters
Name | Description |
---|---|
number |
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.27. joinBy
joinBy(elements: Array<StringCoerceable>, separator: 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 |
---|---|
elements |
The input array. |
separator |
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" }
joinBy(n: Null, separator: Any): Null
Helper function that enables joinBy
to work with a null
value.
1.1.28. keysOf
keysOf<K, V>(obj: { (K)?: V }): Array<K>
Returns an array of keys from key-value pairs within the input object.
The returned keys belong to the Key type. To return each key as a string, you can use namesOf
, instead.
Parameters
Name | Description |
---|---|
object |
The object to evaluate. |
Example
This example returns the keys from the key-value pairs within the input object.
1
2
3
4
%dw 2.0
output application/json
---
{ "keysOf" : keysOf({ "a" : true, "b" : 1}) }
1
{ "keysOf" : ["a","b"] }
Example
This example illustrates a difference between keysOf
and namesOf
.
Notice that keysOf
retains the attributes (name
and lastName
)
and namespaces (xmlns
) from the XML input, while namesOf
returns
null
for them because it does not retain them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
var myVar = read('<users xmlns="http://test.com">
<user name="Mariano" lastName="Achaval"/>
<user name="Stacey" lastName="Duke"/>
</users>', 'application/xml')
output application/json
---
{ keysOfExample: flatten([keysOf(myVar.users) map $.#,
keysOf(myVar.users) map $.@])
}
++
{ namesOfExample: flatten([namesOf(myVar.users) map $.#,
namesOf(myVar.users) map $.@])
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"keysOfExample": [
"http://test.com",
"http://test.com",
{
"name": "Mariano",
"lastName": "Achaval"
},
{
"name": "Stacey",
"lastName": "Duke"
}
],
"namesOfExample": [
null,
null,
null,
null
]
}
keysOf(obj: Null): Null
Helper function that enables keysOf
to work with a null
value.
1.1.29. lastIndexOf
lastIndexOf(array: Array, value: Any): Number
Returns the index of the last occurrence of the specified element in a given
array or -1
if the array does not contain the element.
Parameters
Name | Description |
---|---|
array |
The array of elements to search. |
value |
The value to search. |
Example
This example shows how indexOf
behaves given different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
present: ["a","b","c","d"] lastIndexOf "c",
notPresent: ["x","w","x"] lastIndexOf "c",
presentMoreThanOnce: ["a","b","c","c"] lastIndexOf "c",
}
1
2
3
4
5
{
"present": 2,
"notPresent": -1,
"presentMoreThanOnce": 3
}
lastIndexOf(array: String, value: String): Number
Takes a string as input and returns the index of the last occurrence of
a given search string within the input. The function returns -1
if the
search string is not present in the input.
Parameters
Name | Description |
---|---|
string |
The string to search. |
value |
A string value to search for within the input string. |
Example
This example shows how the indexOf
behaves given different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
output application/json
---
{
present: "abcd" lastIndexOf "c",
notPresent: "xyz" lastIndexOf "c",
presentMoreThanOnce: "abcdc" lastIndexOf "c",
}
1
2
3
4
5
{
"present": 2,
"notPresent": -1,
"presentMoreThanOnce": 4
}
lastIndexOf(array: Null, value: Any): Number
Helper function that enables lastIndexOf
to work with a null
value.
1.1.30. log
log<T>(prefix: String = "", value: T): T
Without changing the value of the input, log
returns the input as a system
log. So this makes it very simple to debug your code, because any expression or subexpression can be wrapped
with log and the result will be printed out without modifying the result of the expression.
The output is going to be printed in application/dw format.
The prefix parameter is optional and allows to easily find the log output.
Use this function to help with debugging DataWeave scripts. A Mule app
outputs the results through the DefaultLoggingService
, which you can see
in the Studio console.
Parameters
Name | Description |
---|---|
prefix |
An optional string that typically describes the log. |
value |
The value to log. |
Example
This example logs the specified message. Note that the DefaultLoggingService
in a Mule app that is running in Studio returns the message
WARNING - "Houston, we have a problem,"
adding the dash -
between the
prefix and value. The Logger component’s LoggerMessageProcessor
returns
the input string "Houston, we have a problem."
, without the WARNING
prefix.
1
2
3
4
%dw 2.0
output application/json
---
log("WARNING", "Houston, we have a problem")
Console Output
1
"WARNING - Houston, we have a problem"
Expression Output
1
"Houston, we have a problem"
Example
This example shows how to log the result of expression myUser.user
without modifying the
original expression myUser.user.friend.name
.
1
2
3
4
5
6
%dw 2.0
output application/json
var myUser = {user: {friend: {name: "Shoki"}, id: 1, name: "Tomo"}, accountId: "leansh" }
---
log("User", myUser.user).friend.name
Console output
1
2
3
4
5
6
7
User - {
friend: {
name: "Shoki"
},
id: 1,
name: "Tomo"
}
Expression Output
1
"Shoki"
1.1.31. lower
lower(text: String): String
Returns the provided string in lowercase characters.
Parameters
Name | Description |
---|---|
text |
The input 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(value: Null): Null
Helper function that enables lower
to work with a null
value.
1.1.32. map
map<T, R>(@StreamCapable items: Array<T>, mapper: (item: T, index: Number) -> R): Array<R>
Iterates over items in an array and outputs the results into a new array.
Parameters
Name | Description |
---|---|
items |
The array to map. |
mapper |
Expression or selector used to act on each |
Example
This example iterates over an input array (["jose", "pedro", "mateo"]
) to
produce an array of DataWeave objects. The anonymous function
(value, index) → {index: value}
maps each item in the input to an object.
As {index: value}
shows, each index from the input array becomes a key
for an output object, and each value of the input array becomes the value of
that object.
1
2
3
4
%dw 2.0
output application/json
---
["jose", "pedro", "mateo"] map (value, index) -> { (index) : value}
1
[ { "0": "jose" }, { "1": "pedro" }, { "2": "mateo" } ]
Example
This example iterates over the input array (['a', 'b', 'c']
) using
an anonymous function that acts on the items and indices of the input. For
each item in the input array, it concatenates the index + 1
(index
plus 1)
with an underscore (_
), and the corresponding value
to return the array,
[ "1_a", "2_b", "3_c" ]
.
1
2
3
4
%dw 2.0
output application/json
---
['a', 'b', 'c'] map ((value, index) -> (index + 1) ++ '_' ++ value)
1
[ "1_a", "2_b", "3_c" ]
Example
If the parameters of the mapper
function are not named, the index can be
referenced with $$
, and the value with $
. This example
iterates over each item in the input array ['joe', 'pete', 'matt']
and returns an array of objects where the index is selected as the key.
The value of each item in the array is selected as the value of
the returned object. Note that the quotes around $$
are necessary to convert the numeric keys to strings.
1
2
3
4
%dw 2.0
output application/json
---
['joe', 'pete', 'matt'] map ( "$$" : $)
1
2
3
4
5
[
{ "0": "joe" },
{ "1": "pete" },
{ "2": "matt" }
]
Example
This example iterates over a list of objects and transform the values into CSV. Each of these objects represent a CSV row. The map
operation generates an object with age
and address
for each entry in the list. $
represents the implicit variable under iteration.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
%dw 2.0
output application/csv
---
[{
"age": 14 ,
"name": "Claire"
}, {
"age": 56,
"name": "Max"
}, {
"age": 89,
"name": "John"
}] map {
age: $.age,
name: $.name
}
1
2
3
4
age,name
14,Claire
56,Max
89,John
map(@StreamCapable value: Null, mapper: (item: Nothing, index: Nothing) -> Any): Null
Helper function that enables map
to work with a null
value.
1.1.33. mapObject
mapObject<K, V>(@StreamCapable object: { (K)?: V }, mapper: (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 |
---|---|
object |
The object to map. |
mapper |
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(value: Null, mapper: (value: Nothing, key: Nothing, index: Nothing) -> Any): Null
Helper function that enables mapObject
to work with a null
value.
Example
Using the previous example, you can test that if the input of the mapObject
is null
, the output result is null
as well. In XML null
values are
written as empty tags. You can change these values by using the writer
property writeNilOnNull=true
.
1
2
3
<?xml version='1.0' encoding='UTF-8'?>
<prices>
</prices>
1
2
3
<?xml version='1.0' encoding='UTF-8'?>
<prices>
</prices>
1.1.34. match
match(text: String, matcher: Regex): Array<String>
Uses a Java regular expression (regex) to match a string and then separates it into capture groups. Returns the results in an array.
Note that you can use match
for pattern matching expressions that include
case
statements.
Parameters
Name | Description |
---|---|
text |
A string. |
matcher |
A Java regex for matching characters in the |
Example
In this example, the regex matches the input email address and contains two
capture groups within parentheses (located before and after the @
). The
result is an array of elements: The first matching the entire regex, the
second matching the initial capture group () in the the regex, the
third matching the last capture group (
[a-z]
).
1
2
3
4
%dw 2.0
output application/json
---
"me@mulesoft.com" match(/([a-z]*)@([a-z]*).com/)
1
2
3
4
5
[
"me@mulesoft.com",
"me",
"mulesoft"
]
Example
This example outputs matches to values in an array that end in 4
. It uses
flatMap
to iterate over and flatten the list.
1
2
3
4
5
6
7
%dw 2.0
var a = '192.88.99.0/24'
var b = '192.168.0.0/16'
var c = '192.175.48.0/24'
output application/json
---
[ a, b, c ] flatMap ( $ match(/.*[$4]/) )
1
[ "192.88.99.0/24", "192.175.48.0/24" ]
match(text: Null, matcher: Any): Null
Helper function that enables match
to work with a null
value.
1.1.35. matches
matches(text: String, matcher: 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 |
---|---|
text |
The input string. |
matcher |
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 ]
matches(text: Null, matcher: Any): false
Helper function that enables matches
to work with a null
value.
1.1.36. max
max<T <: Comparable>(@StreamCapable values: Array<T>): T | Null
Returns the highest Comparable
value in an array.
The items must be of the same type, or the function throws an error. The
function returns null
if the array is empty.
Parameters
Name | Description |
---|---|
values |
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.37. maxBy
maxBy<T>(@StreamCapable array: Array<T>, criteria: (item: T) -> Comparable): T | Null
Iterates over an array and returns the highest value of
Comparable
elements from it.
The items must be of the same type. maxBy
throws an error if they are not,
and the function returns null
if the array is empty.
Parameters
Name | Description |
---|---|
array |
The input array. |
criteria |
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.38. min
min<T <: Comparable>(@StreamCapable values: Array<T>): T | Null
Returns the lowest Comparable
value in an array.
The items must be of the same type or min
throws an error. The function
returns null
if the array is empty.
Parameters
Name | Description |
---|---|
values |
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.39. minBy
minBy<T>(@StreamCapable array: Array<T>, criteria: (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 |
---|---|
item |
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.40. mod
mod(dividend: Number, divisor: Number): Number
Returns the modulo (the remainder after dividing the dividend
by the divisor
).
Parameters
Name | Description |
---|---|
dividend |
The number that serves as the dividend for the operation. |
divisor |
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.41. namesOf
namesOf(obj: Object): Array<String>
Returns an array of strings with the names of all the keys within the given object.
Parameters
Name | Description |
---|---|
obj |
The object to evaluate. |
Example
This example returns the keys from the key-value pairs within the input object.
1
2
3
4
%dw 2.0
output application/json
---
{ "namesOf" : namesOf({ "a" : true, "b" : 1}) }
1
{ "namesOf" : ["a","b"] }
namesOf(obj: Null): Null
Helper function that enables namesOf
to work with a null
value.
1.1.42. now
now(): DateTime
Returns a DateTime
value for the current date and time.
Example
This example uses now()
to return the current date and time as a
DateTime
value. It also shows how to return a date and time
in a specific time zone. Java 8 time zones are supported.
1
2
3
4
5
6
7
%dw 2.0
output application/json
---
{
nowCalled: now(),
nowCalledSpecificTimeZone: now() >> "America/New_York"
}
1
2
3
4
{
"nowCalled": "2019-08-26T13:32:10.64-07:00",
"nowCalledSpecificTimeZone": "2019-08-26T16:32:10.643-04:00"
}
Example
This example shows uses of the now()
function with valid
selectors. It also shows how to get the epoch time with now() as Number
.
For additional examples, see
Date and Time (dw::Core Types).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
%dw 2.0
output application/json
---
{
now: now(),
epochTime : now() as Number,
nanoseconds: now().nanoseconds,
milliseconds: now().milliseconds,
seconds: now().seconds,
minutes: now().minutes,
hour: now().hour,
day: now().day,
month: now().month,
year: now().year,
quarter: now().quarter,
dayOfWeek: now().dayOfWeek,
dayOfYear: now().dayOfYear,
offsetSeconds: now().offsetSeconds,
formattedDate: now() as String {format: "y-MM-dd"},
formattedTime: now() as String {format: "hh:m:s"}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"now": "2019-06-18T16:55:46.678-07:00",
"epochTime": 1560902146,
"nanoseconds": 678000000,
"milliseconds": 678,
"seconds": 46,
"minutes": 55,
"hour": 16,
"day": 18,
"month": 6,
"year": 2019,
"quarter": 2,
"dayOfWeek": 2,
"dayOfYear": 169,
"offsetSeconds": -25200,
"formattedDate": "2019-06-18",
"formattedTime": "04:55:46"
}
1.1.43. onNull
onNull<R>(previous: Null, callback: () -> R): R
Executes a callback function if the preceding expression returns a null
value and then replaces the null
value with the result of the callback.
Parameters
Name | Description |
---|---|
previous |
The value of the preceding expression. |
callback |
Callback that generates a new value if |
Example
This example shows how onNull
behaves when it receives a null
value.
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
---
{
"onNull": []
reduce ((item, accumulator) -> item ++ accumulator)
then ((result) -> sizeOf(result))
onNull "Empty Text"
}
1
2
3
{
"onNull": "Empty Text"
}
onNull<T>(previous: T, callback: () -> Any): T
Helper function that enables onNull
to work with a non-null value.
1.1.44. orderBy
orderBy<K, V, R, O <: { (K)?: V }>(object: O, criteria: (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 |
---|---|
object |
The object to reorder. |
criteria |
The result of the function is used as the criteria to reorder the object. |
Example
This example alphabetically orders the values of each object in the input
array. Note that orderBy($.letter)
produces the same result as
orderBy($[0])
.
1
2
3
4
%dw 2.0
output application/json
---
[{ letter: "e" }, { letter: "d" }] orderBy($.letter)
1
2
3
4
5
6
7
8
[
{
"letter": "d"
},
{
"letter": "e"
}
]
Example
The orderBy
function does not have an option to order in descending order
instead of ascending. In these cases, you can simply invert the order of
the resulting array using -
, for example:
1
2
3
4
%dw 2.0
output application/json
---
orderDescending: ([3,8,1] orderBy -$)
1
{ "orderDescending": [8,3,1] }
orderBy<T, R>(array: Array<T>, criteria: (item: T, index: Number) -> R): Array<T>
Sorts an array using the specified criteria.
Parameters
Name | Description |
---|---|
array |
The array to sort. |
criteria |
The result of the function serves as criteria for sorting the array. It should return a simple value ( |
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
}
]
Example
This example changes the order of the objects in a JSON array. The expression first orders them alphabetically by the value of the Type
key, then reverses the order based on the [-1 to 0]
.
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
%dw 2.0
var myInput = [
{
"AccountNumber": "987999321",
"NameOnAccount": "QA",
"Type": "AAAA",
"CDetail": {
"Status": "Open"
}
},
{
"AccountNumber": "12399978",
"NameOnAccount": "QA",
"Type": "BBBB",
"CDetail": {}
},
{
"AccountNumber": "32199974",
"NameOnAccount": "QA",
"Type": "CCCC",
"CDetail": {}
}
]
output application/json
---
(myInput orderBy $.Type)[-1 to 0]
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
[
{
"AccountNumber": "32199974",
"NameOnAccount": "QA",
"Type": "CCCC",
"CDetail": {
}
},
{
"AccountNumber": "12399978",
"NameOnAccount": "QA",
"Type": "BBBB",
"CDetail": {
}
},
{
"AccountNumber": "987999321",
"NameOnAccount": "QA",
"Type": "AAAA",
"CDetail": {
"Status": "Open"
}
}
]
orderBy(value: Null, criteria: (item: Nothing, index: Nothing) -> Null): Null
Helper function that enables orderBy
to work with a null
value.
1.1.45. pluck
pluck<K, V, R>(@StreamCapable object: { (K)?: V }, mapper: (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 |
---|---|
object |
The object to map. |
mapper |
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(value: Null, mapper: (value: Nothing, key: Nothing, index: Nothing) -> Any): Null
Helper function that enables pluck
to work with a null
value.
1.1.46. pow
pow(base: Number, power: Number): Number
Raises the value of a base
number to the specified power
.
Parameters
Name | Description |
---|---|
base |
A number ( |
power |
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.47. 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.48. randomInt
randomInt(upperBound: Number): Number
Returns a pseudo-random whole number from 0
to the specified number
(exclusive).
Parameters
Name | Description |
---|---|
upperBound |
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.49. read
read(stringToParse: String | Binary, contentType: String = "application/dw", readerProperties: 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 |
---|---|
stringToParse |
The string or binary to read. |
contentType |
A supported format (or content type). Default: |
readerProperties |
Optional: Sets reader configuration properties. For other formats and reader configuration properties, see Supported Data Formats. |
Example
This example reads a JSON object { "hello" : "world" }'
, and it uses the
"application/json"
argument to indicate input content type. By contrast,
the output application/xml
directive in the header of the script tells the
script to transform the JSON content into XML output. Notice that the XML
output uses hello
as the root XML element and world
as the value of
that element. The hello
in the XML corresponds to the key "hello"
in the JSON object, and world
corresponds to the JSON value "world"
.
1
2
3
4
%dw 2.0
output application/xml
---
read('{ "hello" : "world" }','application/json')
1
<?xml version='1.0' encoding='UTF-8'?><hello>world</hello>
Example
This example reads a string as a CSV format without a header and transforms it
to JSON. Notice that it adds column names as keys to the output object. Also,
it appends [0]
to the function call here to select the first index of the
resulting array, which avoids producing the results within an array (with
square brackets surrounding the entire output object).
1
2
3
4
5
%dw 2.0
var myVar = "Some, Body"
output application/json
---
read(myVar,"application/csv",{header:false})[0]
1
{ "column_0": "Some", "column_1": " Body" }
Example
This example reads the specified XML and shows the syntax for a reader property,
in this case, { indexedReader: "false" }
.
1
2
3
4
5
6
7
8
%dw 2.0
output application/xml
---
{
"XML" : read("<prices><basic>9.99</basic></prices>",
"application/xml",
{ indexedReader: "false" })."prices"
}
1
2
3
4
<?xml version='1.0' encoding='UTF-8'?>
<XML>
<basic>9.99</basic>
</XML>
1.1.50. readUrl
readUrl(url: String, contentType: String = "application/dw", readerProperties: Object = {}): Any
Reads a URL, including a classpath-based URL, and returns parsed content.
This function works similar to the read
function.
The classpath-based URL uses the classpath:
protocol prefix, for example:
classpath://myfolder/myFile.txt
where myFolder
is located under
src/main/resources
in a Mule project. Other than the URL, readURL
accepts
the same arguments as read
.
Parameters
Name | Description |
---|---|
url |
The URL string to read. It also accepts a classpath-based URL. |
contentType |
A supported format (or MIME type). Default: |
readerProperties |
Optional: Sets reader configuration properties. For other formats and reader configuration properties, see Supported Data Formats. |
Example
This example reads a JSON object from a URL. (For readability, the output
values shown below are shortened with …
.)
1
2
3
4
%dw 2.0
output application/json
---
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
1
{ "userId": 1, "id": 1, "title": "sunt aut ...", "body": "quia et ..." }
Example
This example reads a JSON object from a myJsonSnippet.json
file located in
the src/main/resources
directory in Studio. (Sample JSON content for that
file is shown in the Input section below.) After reading the file contents,
the script transforms selected fields from JSON to CSV. Reading files
in this way can be useful when trying out a DataWeave script on sample data,
especially when the source data is large and your script is complex.
1
2
3
4
5
%dw 2.0
var myJsonSnippet = readUrl("classpath://myJsonSnippet.json", "application/json")
output application/csv
---
(myJsonSnippet.results map(item) -> item.profile)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{
"results": [
{
"profile": {
"firstName": "john",
"lastName": "doe",
"email": "johndoe@demo.com"
},
"data": {
"interests": [
{
"language": "English",
"tags": [
"digital-strategy:Digital Strategy",
"innovation:Innovation"
],
"contenttypes": []
}
]
}
},
{
"profile": {
"firstName": "jane",
"lastName": "doe",
"email": "janedoe@demo.com"
},
"data": {
"interests": [
{
"language": "English",
"tags": [
"tax-reform:Tax Reform",
"retail-health:Retail Health"
],
"contenttypes": [
"News",
"Analysis",
"Case studies",
"Press releases"
]
}
]
}
}
]
}
1
2
3
firstName,lastName,email
john,doe,johndoe@demo.com
jane,doe,janedoe@demo.com
Example
This example reads a CSV file from a URL, sets reader properties to indicate that there’s no header, and then transforms the data to JSON.
1
2
3
4
%dw 2.0
output application/json
---
readUrl("https://mywebsite.com/data.csv", "application/csv", {"header" : false})
Max,the Mule,MuleSoft
1
2
3
4
5
6
7
[
{
"column_0": "Max",
"column_1": "the Mule",
"column_2": "MuleSoft"
}
]
Example
This example reads a simple dwl
file from the src/main/resources
directory in Studio, then dynamically reads the value of the key name
from it. (Sample content for the input file is shown in the Input
section below.)
1
2
3
4
%dw 2.0
output application/json
---
(readUrl("classpath://name.dwl", "application/dw")).firstName
1
2
3
4
{
"firstName" : "Somebody",
"lastName" : "Special"
}
1
"Somebody"
1.1.51. reduce
reduce<T>(@StreamCapable items: Array<T>, callback: (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 |
Item in the input array. It provides the value to reduce. Can also be referenced as |
acc |
The accumulator. Can also be referenced as The accumulator parameter can be set to an initial value using the
syntax If an initial value for the accumulator is not set, the accumulator is set to the first element of the input array. Then the lambda expression is called with the second element of the input array. The initial value of the accumulator and the lambda expression
dictate the type of result produced by the |
Example
This example returns the sum of the numeric values in the first input array.
1
2
3
4
%dw 2.0
output application/json
---
[2, 3] reduce ($ + $$)
1
5
Example
This example adds the numbers in the sum
example, concatenates the same
numbers in concat
, and shows that an empty array []
(defined in
myEmptyList
) returns null
in emptyList
.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
var myNums = [1,2,3,4]
var myEmptyList = []
output application/json
---
{
"sum" : myNums reduce ($$ + $),
"concat" : myNums reduce ($$ ++ $),
"emptyList" : myEmptyList reduce ($$ ++ $)
}
1
{ "sum": 10, "concat": "1234", "emptyList": null }
Example
This example sets the first element from the first input array to "z"
, and
it adds 3
to the sum of the second input array. In multiply
, it shows how
to multiply each value in an array by the next
([2,3,3] reduce ((item, acc) → acc * item)
) to
produce a final result of 18
(= 2 * 3 * 3
). The final example,
multiplyAcc
, sets the accumulator to 3
to multiply the result of
acc * item
(= 12
) by 3
(that is, 3 (2 * 2 * 3) = 36
), as shown in
the output.
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
---
{
"concat" : ["a", "b", "c", "d"] reduce ((item, acc = "z") -> acc ++ item),
"sum": [0, 1, 2, 3, 4, 5] reduce ((item, acc = 3) -> acc + item),
"multiply" : [2,3,3] reduce ((item, acc) -> acc * item),
"multiplyAcc" : [2,2,3] reduce ((item, acc = 3) -> acc * item)
}
1
{ "concat": "zabcd", "sum": 18, "multiply": 18, "multiplyAcc": 36 }
Example
This example shows a variety of uses of reduce
, including its application to
arrays of boolean values and objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
%dw 2.0
output application/json
var myVar =
{
"a": [0, 1, 2, 3, 4, 5],
"b": ["a", "b", "c", "d", "e"],
"c": [{ "letter": "a" }, { "letter": "b" }, { "letter": "c" }],
"d": [true, false, false, true, true]
}
---
{
"a" : [0, 1, 2, 3, 4, 5] reduce $$,
"b": ["a", "b", "c", "d", "e"] reduce $$,
"c": [{ "letter": "a" }, { "letter": "b" }, { "letter": "c" }] reduce ((item, acc = "z") -> acc ++ item.letter),
"d": [{ letter: "a" }, { letter: "b" }, { letter: "c" }] reduce $$,
"e": [true, false, false, true, true] reduce ($$ and $),
"f": [true, false, false, true, true] reduce ((item, acc) -> acc and item),
"g": [true, false, false, true, true] reduce ((item, acc = false) -> acc and item),
"h": [true, false, false, true, true] reduce $$,
"i": myVar.a reduce ($$ + $),
"j": myVar.a reduce ((item, acc) -> acc + item),
"k": myVar.a reduce ((item, acc = 3) -> acc + item),
"l": myVar.a reduce $$,
"m": myVar.b reduce ($$ ++ $),
"n": myVar.b reduce ((item, acc) -> acc ++ item),
"o": myVar.b reduce ((item, acc = "z") -> acc ++ item),
"p": myVar.b reduce $$,
"q": myVar.c reduce ((item, acc = "z") -> acc ++ item.letter),
"r": myVar.c reduce $$,
"s": myVar.d reduce ($$ and $),
"t": myVar.d reduce ((item, acc) -> acc and item),
"u": myVar.d reduce ((item, acc = false) -> acc and item),
"v": myVar.d reduce $$,
"w": ([0, 1, 2, 3, 4] reduce ((item, acc = {}) -> acc ++ { a: item })) pluck $,
"x": [] reduce $$,
"y": [] reduce ((item,acc = 0) -> acc + item)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"a": 0,
"b": "a",
"c": "zabc",
"d": { "letter": "a" },
"e": false,
"f": false,
"g": false,
"h": true,
"i": 15,
"j": 15,
"k": 18,
"l": 0,
"m": "abcde",
"n": "abcde",
"o": "zabcde",
"p": "a",
"q": "zabc",
"r": { "letter": "a" },
"s": false,
"t": false,
"u": false,
"v": true,
"w": [ 0,1,2,3,4 ],
"x": null,
"y": 0
}
reduce<T, A>(@StreamCapable items: Array<T>, callback: (item: T, accumulator: A) -> A): A
reduce(@StreamCapable text: String, callback: (item: String, accumulator: String) -> String): String
Applies a reduction expression to the characters in a string.
For each character of the input string, 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 character
and the current accumulator value.
Note that if the string is empty and no default value is set on the accumulator parameter, an empty string is returned.
Parameters
Name | Description |
---|---|
text |
The string to reduce. |
callback |
The function to apply. |
Example
This example shows how reduce
can be used to reverse a string.
1
2
3
4
%dw 2.0
output application/json
---
"hello world" reduce (item, acc = "") -> item ++ acc
1
"dlrow olleh"
reduce<A>(@StreamCapable text: String, callback: (item: String, accumulator: A) -> A): A
reduce<T, A>(@StreamCapable items: Null, callback: (item: T, accumulator: A) -> A): Null
Helper function that enables reduce
to work with a null
value.
1.1.52. replace
replace(text: String, matcher: 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 |
---|---|
text |
A string to match. |
matcher |
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(text: String, matcher: 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 |
---|---|
text |
The string to match. |
matcher |
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" }
replace(text: Null, matcher: Any): ((Nothing, Nothing) -> Any) -> Null
Helper function that enables replace
to work with a null
value.
1.1.53. round
round(number: Number): Number
Rounds a number up or down to the nearest whole number.
Parameters
Name | Description |
---|---|
number |
The number to evaluate. |
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.54. scan
scan(text: String, matcher: 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 |
---|---|
text |
The input string to scan. |
regex |
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" ]
]
scan(text: Null, matcher: Any): Null
Helper function that enables scan
to work with a null
value.
1.1.55. sizeOf
sizeOf(array: Array<Any>): Number
Returns the number of elements in an array. It returns 0
if the array
is empty.
This version of sizeOf
takes an array or an array of arrays as input.
Other versions act on arrays of objects, strings, or binary values.
Parameters
Name | Description |
---|---|
array |
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: Object): Number
Returns the number of key-value pairs in an object.
This function accepts an array of objects. Returns 0
if the input object is
empty.
Parameters
Name | Description |
---|---|
object |
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: Binary): Number
Returns the number of elements in an array of binary values.
Parameters
Name | Description |
---|---|
binary |
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(text: String): Number
Returns the number of characters (including white space) in an string.
Returns 0
if the string is empty.
Parameters
Name | Description |
---|---|
text |
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
}
sizeOf(n: Null): Null
Helper function that enables sizeOf
to work with a null
value.
1.1.56. splitBy
splitBy(text: String, regex: Regex): Array<String>
Splits a string into a string array based on a value that matches part of that string. It filters out the matching part from the returned array.
This version of splitBy
accepts a Java regular expression (regex) to
match the input string. The regex can match any character in the input
string. Note that splitBy
performs the opposite operation of joinBy
.
Parameters
Name | Description |
---|---|
text |
The input string to split. |
regex |
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" ]
}
}
Example
This example splits the number by .
and applies the index selector [0]
to
the result of the splitBy function. The splitBy returns ["192", "88", "99", "0"]
so the index * selector [0]
just returns the first element in the array ("192").
1
2
3
4
%dw 2.0
output application/json
---
("192.88.99.0" splitBy("."))[0]
1
"192"
Example
This example uses a Java regular expression to split a string by .
at every
point the input string matches the regex. Note that the regular expression
does not consider the periods between the backticks `
.
1
2
3
4
%dw 2.0
output application/json
---
'root.sources.data.`test.branch.BranchSource`.source.traits' splitBy(/[.](?=(?:[^`]*`[^`]*`)*[^`]*$)/)
1
2
3
4
5
6
7
8
[
"root",
"sources",
"data",
"`test.branch.BranchSource`",
"source",
"traits"
]
splitBy(text: String, separator: 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 |
---|---|
text |
The string to split. |
separator |
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"]
}
}
splitBy(text: Null, separator: Any)
Helper function that enables splitBy
to work with a null
value.
1.1.57. sqrt
sqrt(number: Number): Number
Returns the square root of a number.
Parameters
Name | Description |
---|---|
number |
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.58. startsWith
startsWith(text: String, prefix: String): Boolean
Returns true
or false
depending on whether the input string starts with a
matching prefix.
Parameters
Name | Description |
---|---|
text |
The input string. |
prefix |
A string that identifies the prefix. |
Example
This example indicates whether the strings start with a given prefix.
Note that you can use the startsWith(text,prefix)
or
text startsWith(prefix)
notation (for example,
startsWith("Mari","Mar")
or "Mari" startsWith("Mar")
).
1
2
3
4
%dw 2.0
output application/json
---
[ "Mari" startsWith("Mar"), "Mari" startsWith("Em") ]
1
[ true, false ]
startsWith(text: Null, prefix: Any): false
Helper function that enables startsWith
to work with a null
value.
1.1.59. sum
sum(values: 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 |
---|---|
values |
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.60. then
then(value: Null, callback: (previousResult: Nothing) -> Any): Null
Helper function that enables then
to work with a null
value.
then<T, R>(previous: T, callback: (result: T) -> R): R
This function works as a pipe that passes the value returned from the
preceding expression to the next (a callback) only if the value returned
by the preceding expression is not null
.
Parameters
Name | Description |
---|---|
previous |
The value of the preceding expression. |
callback |
Callback that processes the result of |
Example
This example shows how to use then
to chain and continue processing
the result of the previous expression.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
%dw 2.0
output application/json
---
{
"chainResult": ["mariano", "de Achaval"]
reduce ((item, accumulator) -> item ++ accumulator)
then ((result) -> sizeOf(result)),
"referenceResult" : ["mariano", "de Achaval"]
map ((item, index) -> upper(item))
then {
name: $[0],
lastName: $[1],
length: sizeOf($)
},
"onNullReturnNull": []
reduce ((item, accumulator) -> item ++ accumulator)
then ((result) -> sizeOf(result))
}
1
2
3
4
5
6
7
8
9
{
"chainResult": 17,
"referenceResult": {
"name": "MARIANO",
"lastName": "DE ACHAVAL",
"length": 2
},
"onNullReturnNull": null
}
1.1.61. to
to(from: Number, to: Number): Range
Returns a range with the specified boundaries.
The upper boundary is inclusive.
Parameters
Name | Description |
---|---|
from |
|
to |
|
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] }
Example
DataWeave treats a string as an array of characters. This example applies to
to a string.
1
2
3
4
5
6
7
8
9
%dw 2.0
var myVar = "Hello World!"
output application/json
---
{
indices2to6 : myVar[2 to 6],
indicesFromEnd : myVar[6 to -1],
reversal : myVar[11 to -0]
}
1
2
3
4
5
{
"indices2to6": "llo W",
"indicesFromEnd": "World!",
"reversal": "!dlroW olleH"
}
1.1.62. trim
trim(text: String): String
Removes any blank spaces from the beginning and end of a string.
Parameters
Name | Description |
---|---|
text |
The string from which to remove any blank spaces. |
Example
This example trims a string. Notice that it does not remove any spaces from the middle of the string, only the beginning and end.
1
2
3
4
%dw 2.0
output application/json
---
{ "trim": trim(" my really long text ") }
1
{ "trim": "my really long text" }
Example
This example shows how trim
handles a variety strings and how it
handles a null value.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
---
{
"null": trim(null),
"empty": trim(""),
"blank": trim(" "),
"noBlankSpaces": trim("abc"),
"withSpaces": trim(" abc ")
}
1
2
3
4
5
6
7
{
"null": null,
"empty": "",
"blank": "",
"noBlankSpaces": "abc",
"withSpaces": "abc"
}
trim(value: Null): Null
Helper function that enables trim
to work with a null
value.
1.1.63. typeOf
typeOf<T>(value: T): Type<T>
Returns the primitive data type of a value, such as String
.
A value’s type is taken from its runtime representation and is never one of
the arithmetic types (intersection, union, Any
, or Nothing
) nor a type
alias. If present, metadata of a value is included in the result of
typeOf
(see metadataOf).
Parameters
Name | Description |
---|---|
value |
Input value to evaluate. |
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" ]
Example
This example shows that the type of a value is independent of the type with which it is declared.
1
2
3
4
5
6
7
%dw 2.0
output application/json
var x: String | Number = "clearly a string"
var y: "because" = "because"
---
[typeOf(x), typeOf(y)]
1
["String", "String"]
1.1.64. unzip
unzip<T>(items: 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 |
---|---|
items |
The input array of arrays. |
Example
This example unzips an array of arrays. It outputs the first index of each
sub-array into one array [ 0, 1, 2, 3 ]
, and the second index of each into
another [ "a", "b", "c", "d" ]
.
1
2
3
4
%dw 2.0
output application/json
---
unzip([ [0,"a"], [1,"b"], [2,"c"],[ 3,"d"] ])
1
[ [ 0, 1, 2, 3 ], [ "a", "b", "c", "d" ] ]
Example
This example unzips an array of arrays. Notice that the number of elements in the input arrays is not all the same. The function creates only as many full sub-arrays as it can, in this case, just one.
1
2
3
4
%dw 2.0
output application/json
---
unzip([ [0,"a"], [1,"a","foo"], [2], [3,"a"] ])
1
[0,1,2,3]
1.1.65. upper
upper(text: String): String
Returns the provided string in uppercase characters.
Parameters
Name | Description |
---|---|
text |
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(value: Null): Null
Helper function that enables upper
to work with a null
value.
1.1.66. uuid
uuid(): String
Returns a v4 UUID using random numbers as the source.
Example
This example generates a random v4 UUID.
1
2
3
4
%dw 2.0
output application/json
---
uuid()
1
"7cc64d24-f2ad-4d43-8893-fa24a0789a99"
1.1.67. valuesOf
valuesOf<K, V>(obj: { (K)?: V }): Array<V>
Returns an array of the values from key-value pairs in an object.
Parameters
Name | Description |
---|---|
obj |
The object to evaluate. |
Example
This example returns the values of key-value pairs within the input object.
1
2
3
4
%dw 2.0
output application/json
---
{ "valuesOf" : valuesOf({a: true, b: 1}) }
1
{ "valuesOf" : [true,1] }
valuesOf(obj: Null): Null
Helper function that enables valuesOf
to work with a null
value.
1.1.68. with
with<V, U, R, X>(toBeReplaced: ((V, U) -> R) -> X, replacer: (V, U) -> R): X
Helper function that specifies a replacement element. This function is used with replace
, update
or mask
to perform data substitutions.
Parameters
Name | Description |
---|---|
toBeReplaced |
The value to be replaced. |
replacer |
The replacement value for the input value. |
Example
This example replaces all numbers in a string with "x" characters. The replace
function specifies the base string and a regex to select the characters to replace, and with
provides the replacement string to use.
1
2
3
4
%dw 2.0
output application/json
---
{ "ssn" : "987-65-4321" replace /[0-9]/ with("x") }
1
{ "ssn": "xxx-xx-xxxx" }
1.1.69. write
write(value: Any, contentType: String = "application/dw", writerProperties: 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.
It returns a String
value for all text-based data formats (such as XML, JSON , CSV)
and a Binary
value for all the binary formats (such as Excel, MultiPart, OctetStream).
Parameters
Name | Description |
---|---|
value |
The value to write. The value can be of any supported data type. |
contentType |
A supported format (or MIME type) to write. Default: |
writerProperties |
Optional: Sets writer configuration properties. For writer configuration properties (and other supported MIME types), see Supported Data Formats. |
Example
This example writes the string world
in plain text (text/plain"
). It
outputs that string as the value of a JSON object with the key hello
.
1
2
3
4
%dw 2.0
output application/json
---
{ hello : write("world", "text/plain") }
1
{ "hello": "world" }
Example
This example takes JSON input and writes the payload to a CSV format that uses a
pipe (|
) separator and includes the header (matching keys in the JSON objects).
Note that if you instead use "header":false
in your script, the output will
lack the Name|Email|Id|Title
header in the output.
1
2
3
4
%dw 2.0
output application/xml
---
{ "output" : write(payload, "application/csv", {"header":true, "separator" : "|"}) }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
{
"Name": "Mr White",
"Email": "white@mulesoft.com",
"Id": "1234",
"Title": "Chief Java Prophet"
},
{
"Name": "Mr Orange",
"Email": "orange@mulesoft.com",
"Id": "4567",
"Title": "Integration Ninja"
}
]
1
2
3
4
5
<?xml version="1.0" encoding="US-ASCII"?>
<output>Name|Email|Id|Title
Mr White|white@mulesoft.com|1234|Chief Java Prophet
Mr Orange|orange@mulesoft.com|4567|Integration Ninja
</output>
1.1.70. xsiType
xsiType(name: String, namespace: Namespace)
Creates a xsi:type
type attribute. This method returns an object, so it must be used with dynamic attributes.
Parameters
Name | Description |
---|---|
name |
The name of the schema |
namespace |
The namespace of that type. |
Example
This example shows how the xsiType
behaves under different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/xml
ns acme http://acme.com
---
{
user @((xsiType("user", acme))): {
name: "Peter",
lastName: "Parker"
}
}
1
2
3
4
5
<?xml version='1.0' encoding='UTF-8'?>
<user xsi:type="acme:user" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:acme="http://acme.com">
<name>Peter</name>
<lastName>Parker</lastName>
</user>
1.1.71. zip
zip<T, R>(left: Array<T>, right: 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 |
---|---|
left |
The array on the left-hand side of the function. |
right |
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, which represents the null
value.
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.
1
{ l: LEFT, r: RIGHT }
1.2.22. Period
A period.
1
Period
1.2.23. Range
A Range
type represents a sequence of numbers.
1
Range
1.2.24. Regex
A Java regular expression (regex) type.
1
Regex
1.2.25. SimpleType
A union type that represents all the simple types.
1
String | Boolean | Number | DateTime | LocalDateTime | Date | LocalTime | Time | TimeZone | Period
1.2.26. String
String
type
1
String
1.2.27. StringCoerceable
A union type of all the types that can be coerced to String type.
1
String | Boolean | Number | DateTime | LocalDateTime | Date | LocalTime | Time | TimeZone | Period | Key | Binary | Uri | Type<Any> | Regex | Namespace
1.2.28. Time
A time in a specific TimeZone
. For example: |22:10:18Z|
1
Time
1.2.29. TimeZone
A time zone.
1
TimeZone
1.2.30. Type
A type in the DataWeave type system.
1
Type
1.2.31. Uri
A URI.
1
Uri
1.3. Annotations
1.3.1. @AnnotationTarget(targets: Array<"Function" | "Parameter" | "Variable" | "Import" | "Type" | "Version" | "Namespace">)
Annotation that limits the application of an annotation. An example is
@AnnotationTarget(targets = ["Function", "Variable"])
, which limits
the scope of the annotation annotation TailRec()
to functions and
variables. If no AnnotationTarget
is specified, an annotation can
apply to any valid target.
Annotation Targets:
-
Parameter
: For function parameters. -
Function
: For function definitions. -
Variable
: For variable definitions. -
Import
: For import definitions.
1.3.2. @Deprecated(since: String, replacement: String)
Annotation that marks a function as deprecated.
1.3.3. @DesignOnlyType()
Annotation that marks a parameter type as design only to indicate that the field type is validated only at design time. At runtime, only minimal type validation takes place. This annotation is useful for performance, especially with complex Object types.
1.3.4. @Experimental()
Annotation that identifies a feature as experimental and subject to change or removal in the future.
1.3.5. @GlobalDescription()
Annotation used to identify the function description to use for the function’s documentation. This annotation is useful for selecting the correct function description when the function is overloaded.
1.3.6. @Interceptor(interceptorFunction: String | (annotationArgs: Object, targetFunctionName: String, args: Array<Any>, callback: (args: Array<Any>) -> Any) -> Any)
Annotation that marks another annotation as an Interceptor so that the
marked annotation will wrap an annotated function with an interceptorFunction
.
An example is the RuntimePrivilege
annotation, which is annotated by
@Interceptor(interceptorFunction = "@native system::SecurityManagerCheckFunctionValue")
.
The readUrl
function definition is annotated by @RuntimePrivilege(requires = "Resource")
.
1.3.7. @Internal(permits: Array<String>)
Annotation that marks a function as internal and not to be used.
_Introduced in DataWeave 2.4.0. Supported by Mule 4.4.0 and later._
1.3.8. @Labels(labels: Array<String>)
Annotation for labeling a function or variable definition so that it
becomes more easy to discover. An example is
@Labels(labels =["append", "concat"])
.
1.3.9. @Lazy()
Annotation that marks a variable declaration for lazy initialization.
1.3.10. @RuntimePrivilege(requires: String)
Annotation used to indicate that a function requires runtime privileges to
execute. An example is @RuntimePrivilege(requires = "Resource")
, which
annotates the readUrl
function definition.
1.3.11. @Since(version: String)
Annotation that identifies the DataWeave version in which the annotated
functionality was introduced. An example is @Since(version = "2.4.0")
.
Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
1.3.12. @StreamCapable()
Annotation that marks a parameter as stream capable, which means that this
field will consume an array of objects in a forward-only manner. Examples of
functions with @StreamCapable
fields are map
, mapObject
, and pluck
.
1.3.13. @TailRec()
Annotation that marks a function as tail recursive. If a function with this annotation is not tail recursive, the function will fail.
1.3.14. @UntrustedCode(privileges: Array<String>)
Annotation that marks a script as untrusted, which means that the script has no privileges. For example, such a script cannot gain access to environment variables or read a resource from a URL.
1.4. Namespaces
1.4.1. xsi = http://www.w3.org/2001/XMLSchema-instance
Namespace declaration of XMLSchema.
2. 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.
2.1. Functions
2.1.1. countBy
countBy<T>(array: Array<T>, matchingFunction: (T) -> Boolean): Number
Counts the elements in an array that return true
when the matching function is applied to the value of each element.
Parameters
Name | Description |
---|---|
array |
The input array that contains elements to match. |
matchingFunction |
A function to apply to elements in the input array. |
Example
This example counts the number of elements in the input array ([1, 2, 3, 4]) that
return true
when the function (($ mod 2) == 0)
is applied their values. In this
case, the values of two of the elements, both 2
and 4
, match because
2 mod 2 == 0
and 4 mod 2 == 0
. As a consequence, the countBy
function returns 2
.
Note that mod
returns the modulus of the operands.
1
2
3
4
5
%dw 2.0
import * from dw::core::Arrays
output application/json
---
{ "countBy" : [1, 2, 3, 4] countBy (($ mod 2) == 0) }
1
{ "countBy": 2 }
countBy(array: Null, matchingFunction: (Nothing) -> Any): Null
Helper function that enables countBy
to work with a null
value.
2.1.2. divideBy
divideBy<T>(items: Array<T>, amount: Number): Array<Array<T>>
Breaks up an array into sub-arrays that contain the specified number of elements.
When there are fewer elements in the input array than the specified number, the function fills the sub-array with those elements. When there are more elements, the function fills as many sub-arrays needed with the extra elements.
Parameters
Name | Description |
---|---|
items |
Items in the input array. |
amount |
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 ]
]
}
]
}
divideBy(items: Null, amount: Any): Null
Helper function that enables divideBy
to work with a null
value.
2.1.3. drop
drop<T>(array: Array<T>, n: Number): Array<T>
Drops the first n
elements. It returns the original array when n <= 0
and an empty array when n > sizeOf(array)
.
Parameters
Name | Description |
---|---|
array |
The left array of elements. |
n |
The number of elements to take. |
Example
This example returns an array that only contains the third element of the input array. It drops the first two elements from the output.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
var users = ["Mariano", "Leandro", "Julian"]
output application/json
---
drop(users, 2)
1
2
3
[
"Julian"
]
drop(array: Null, n: Any): Null
Helper function that enables drop
to work with a null
value.
2.1.4. dropWhile
dropWhile<T>(array: Array<T>, condition: (item: T) -> Boolean): Array<T>
Drops elements from the array while the condition is met but stops the selection process when it reaches an element that fails to satisfy the condition.
Parameters
Name | Description |
---|---|
array |
The array of elements. |
condition |
The condition (or expression) used to match an element in the array. |
Example
This example returns an array that omits elements that are less than or equal to 2
.
The last two elements (2
and 1
) are included in the output array because the
function stops dropping elements when it reaches the 3
, which is greater than 2
.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,3,2,1]
---
arr dropWhile $ < 3
1
2
3
4
5
[
3,
2,
1
]
dropWhile(array: Null, condition: (item: Nothing) -> Any): Null
Helper function that enables dropWhile
to work with a null
value.
2.1.5. every
every<T>(list: Array<T>, condition: (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 |
---|---|
list |
The input array. |
condition |
A condition (or expression) to apply to elements in the input array. |
Example
This example applies a variety of expressions to the input arrays. The $
references values of the elements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
%dw 2.0
import * from dw::core::Arrays
var arr0 = [] as Array<Number>
output application/json
---
{ "results" : [
"ok" : [
[1,1,1] every ($ == 1),
[1] every ($ == 1)
],
"err" : [
[1,2,3] every ((log('should stop at 2 ==', $) mod 2) == 1),
[1,1,0] every ($ == 1),
[0,1,1,0] every (log('should stop at 0 ==', $) == 1),
[1,2,3] every ($ == 1),
arr0 every true,
]
]
}
1
2
3
4
5
6
7
8
9
10
{
"results": [
{
"ok": [ true, true ]
},
{
"err": [ false, false, false, false, false ]
}
]
}
every(value: Null, condition: (Nothing) -> Any): Boolean
Helper function that enables every
to work with a null
value.
2.1.6. firstWith
firstWith<T>(array: Array<T>, condition: (item: T, index: Number) -> Boolean): T | Null
Returns the first element that satisfies the condition, or returns null
if no
element meets the condition.
Parameters
Name | Description |
---|---|
array |
The array of elements to search. |
condition |
The condition to satisfy. |
Example
This example shows how firstWith
behaves when an element matches and when an element does not match.
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
import firstWith from dw::core::Arrays
var users = [{name: "Mariano", lastName: "Achaval"}, {name: "Ana", lastName: "Felisatti"}, {name: "Mariano", lastName: "de Sousa"}]
---
{
a: users firstWith ((user, index) -> user.name == "Mariano"),
b: users firstWith ((user, index) -> user.name == "Peter")
}
1
2
3
4
5
6
7
{
"a": {
"name": "Mariano",
"lastName": "Achaval"
},
"b": null
}
firstWith(array: Null, condition: (item: Nothing, index: Nothing) -> Any): Null
Helper function that enables firstWith
to work with a null
value.
2.1.7. indexOf
indexOf<T>(array: Array<T>, toFind: T): Number
Returns the index of the first occurrence of an element within the array. If the value is not found, the function returns -1
.
Parameters
Name | Description |
---|---|
array |
The array of elements. |
toFind |
The element to find. |
Example
This example returns the index of the matching value from the input array.
The index of "Julian"
is 2
.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var users = ["Mariano", "Leandro", "Julian"]
---
indexOf(users, "Julian")
1
2
2.1.8. indexWhere
indexWhere<T>(array: Array<T>, condition: (item: T) -> Boolean): Number
Returns the index of the first occurrence of an element that matches a
condition within the array. If no element matches the condition, the function returns -1
.
Parameters
Name | Description |
---|---|
array |
The array of elements. |
condition |
The condition (or expression) used to match an element in the array. |
Example
This example returns the index of the value from the input array that
matches the condition in the lambda expression,
(item) → item startsWith "Jul"
.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var users = ["Mariano", "Leandro", "Julian"]
---
users indexWhere (item) -> item startsWith "Jul"
1
2
indexWhere(array: Null, condition: (item: Nothing) -> Any): Null
Helper function that enables indexWhere
to work with a null
value.
2.1.9. join
join<L <: Object, R <: Object>(left: Array<L>, right: Array<R>, leftCriteria: (leftValue: L) -> String, rightCriteria: (rightValue: R) -> String): Array<Pair<L, R>>
Joins two arrays of objects by a given ID criteria.
join
returns an array all the left
items, merged by ID with any
right items that exist.
Parameters
Name | Description |
---|---|
left |
The left-side array of objects. |
right |
The right-side array of objects. |
leftCriteria |
The criteria used to extract the ID for the left collection. |
rightCriteria |
The criteria used to extract the ID for the right collection. |
Example
This example shows how join behaves. Notice that the output only includes
objects where the values of the input user.id
and product.ownerId
match.
The function includes the "l"
and "r"
keys in the output.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Arrays
var users = [{id: "1", name:"Mariano"},{id: "2", name:"Leandro"},{id: "3", name:"Julian"},{id: "5", name:"Julian"}]
var products = [{ownerId: "1", name:"DataWeave"},{ownerId: "1", name:"BAT"}, {ownerId: "3", name:"DataSense"}, {ownerId: "4", name:"SmartConnectors"}]
output application/json
---
join(users, products, (user) -> user.id, (product) -> product.ownerId)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "DataWeave"
}
},
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "BAT"
}
},
{
"l": {
"id": "3",
"name": "Julian"
},
"r": {
"ownerId": "3",
"name": "DataSense"
}
}
]
2.1.10. leftJoin
leftJoin<L <: Object, R <: Object>(left: Array<L>, right: Array<R>, leftCriteria: (leftValue: L) -> String, rightCriteria: (rightValue: R) -> String): Array<{ l: L, r?: R }>
Joins two arrays of objects by a given ID criteria.
leftJoin
returns an array all the left
items, merged by ID with any right
items that meet the joining criteria.
Parameters
Name | Description |
---|---|
left |
The left-side array of objects. |
right |
The right-side array of objects. |
leftCriteria |
The criteria used to extract the ID for the left collection. |
rightCriteria |
The criteria used to extract the ID for the right collection. |
Example
This example shows how join behaves. Notice that it returns all objects from
the left-side array (left
) but only joins items from the right-side array
(right
) if the values of the left-side user.id
and right-side
product.ownerId
match.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Arrays
var users = [{id: "1", name:"Mariano"},{id: "2", name:"Leandro"},{id: "3", name:"Julian"},{id: "5", name:"Julian"}]
var products = [{ownerId: "1", name:"DataWeave"},{ownerId: "1", name:"BAT"}, {ownerId: "3", name:"DataSense"}, {ownerId: "4", name:"SmartConnectors"}]
output application/json
---
leftJoin(users, products, (user) -> user.id, (product) -> product.ownerId)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
[
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "DataWeave"
}
},
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "BAT"
}
},
{
"l": {
"id": "2",
"name": "Leandro"
}
},
{
"l": {
"id": "3",
"name": "Julian"
},
"r": {
"ownerId": "3",
"name": "DataSense"
}
},
{
"l": {
"id": "5",
"name": "Julian"
}
}
]
2.1.11. outerJoin
outerJoin<L <: Object, R <: Object>(left: Array<L>, right: Array<R>, leftCriteria: (leftValue: L) -> String, rightCriteria: (rightValue: R) -> String): Array<{ l?: L, r?: R }>
Joins two array of objects by a given ID
criteria.
outerJoin
returns an array with all the left
items, merged by ID
with the right
items in cases where any exist, and it returns right
items that are not present in the left
.
Parameters
Name | Description |
---|---|
left |
The left-side array of objects. |
right |
The right-side array of objects. |
leftCriteria |
The criteria used to extract the ID for the left collection. |
rightCriteria |
The criteria used to extract the ID for the right collection. |
Example
This example shows how join behaves. Notice that the output includes
objects where the values of the input user.id
and product.ownerId
match,
and it includes objects where there is no match for the value of the
user.id
or product.ownerId
.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Arrays
var users = [{id: "1", name:"Mariano"},{id: "2", name:"Leandro"},{id: "3", name:"Julian"},{id: "5", name:"Julian"}]
var products = [{ownerId: "1", name:"DataWeave"},{ownerId: "1", name:"BAT"}, {ownerId: "3", name:"DataSense"}, {ownerId: "4", name:"SmartConnectors"}]
output application/json
---
outerJoin(users, products, (user) -> user.id, (product) -> product.ownerId)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
[
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "DataWeave"
}
},
{
"l": {
"id": "1",
"name": "Mariano"
},
"r": {
"ownerId": "1",
"name": "BAT"
}
},
{
"l": {
"id": "2",
"name": "Leandro"
}
},
{
"l": {
"id": "3",
"name": "Julian"
},
"r": {
"ownerId": "3",
"name": "DataSense"
}
},
{
"l": {
"id": "5",
"name": "Julian"
}
},
{
"r": {
"ownerId": "4",
"name": "SmartConnectors"
}
}
]
2.1.12. partition
partition<T>(array: Array<T>, condition: (item: T) -> Boolean): { success: Array<T>, failure: Array<T> }
Separates the array into the elements that satisfy the condition from those that do not.
Parameters
Name | Description |
---|---|
array |
The array of elements to split. |
condition |
The condition (or expression) used to match an element in the array. |
Example
This example partitions numbers found within an input array. The
even numbers match the criteria set by the lambda expression
(item) → isEven(item)
. The odd do not. The function generates the
"success"
and "failure"
keys within the output object.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,3,4,5]
---
arr partition (item) -> isEven(item)
1
2
3
4
5
6
7
8
9
10
11
12
{
"success": [
0,
2,
4
],
"failure": [
1,
3,
5
]
}
partition(array: Null, condition: (item: Nothing) -> Any): Null
Helper function that enables partition
to work with a null
value.
2.1.13. slice
slice<T>(array: Array<T>, from: Number, until: Number): Array<T>
Selects the interval of elements that satisfy the condition:
from <= indexOf(array) < until
Parameters
Name | Description |
---|---|
array |
The array of elements. |
from |
The starting index of the interval of elements to include from the array. |
until |
The ending index of the interval of elements to include from the array. |
Example
This example returns an array that contains the values of indices 1, 2, and 3 from the input array. It excludes the values of indices 0, 4, and 5.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,3,4,5]
---
slice(arr, 1, 4)
1
2
3
4
5
[
1,
2,
3
]
slice(array: Null, from: Any, until: Any): Null
Helper function that enables slice
to work with a null
value.
2.1.14. some
some<T>(list: Array<T>, condition: (T) -> Boolean): Boolean
Returns true
if at least one element in the array matches the specified condition.
The function stops iterating after the first element that matches the condition is found.
Parameters
Name | Description |
---|---|
list |
The input array. |
condition |
A condition (or expression) used to match elements in the array. |
Example
This example applies a variety of expressions to elements of several input arrays.
The $
in the condition is the default parameter for the current element of the
array that the condition evaluates.
Note that you can replace the default $
parameter with a lambda expression that
contains a named parameter for the current array element.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
%dw 2.0
import * from dw::core::Arrays
output application/json
---
{ "results" : [
"ok" : [
[1,2,3] some (($ mod 2) == 0),
[1,2,3] some ((nextNum) -> (nextNum mod 2) == 0),
[1,2,3] some (($ mod 2) == 1),
[1,2,3,4,5,6,7,8] some (log('should stop at 2 ==', $) == 2),
[1,2,3] some ($ == 1),
[1,1,1] some ($ == 1),
[1] some ($ == 1)
],
"err" : [
[1,2,3] some ($ == 100),
[1] some ($ == 2)
]
]
}
1
2
3
4
5
6
7
8
9
10
{
"results": [
{
"ok": [ true, true, true, true, true, true, true ]
},
{
"err": [ false, false ]
}
]
}
some(list: Null, condition: (Nothing) -> Any): Boolean
Helper function that enables some
to work with a null
value.
2.1.15. splitAt
splitAt<T>(array: Array<T>, n: Number): Pair<Array<T>, Array<T>>
Splits an array into two at a given position.
Parameters
Name | Description |
---|---|
array |
The array of elements. |
n |
The index at which to split the array. |
Example
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var users = ["Mariano", "Leandro", "Julian"]
---
users splitAt 1
1
2
3
4
5
6
7
8
9
{
"l": [
"Mariano"
],
"r": [
"Leandro",
"Julian"
]
}
splitAt(array: Null, n: Any): Null
Helper function that enables splitAt
to work with a null
value.
2.1.16. splitWhere
splitWhere<T>(array: Array<T>, condition: (item: T) -> Boolean): Pair<Array<T>, Array<T>>
Splits an array into two at the first position where the condition is met.
Parameters
Name | Description |
---|---|
array |
The array of elements to split. |
condition |
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"
]
}
splitWhere(array: Null, condition: (item: Nothing) -> Any): Null
Helper function that enables splitWhere
to work with a null
value.
2.1.17. sumBy
sumBy<T>(array: Array<T>, numberSelector: (T) -> Number): Number
Returns the sum of the values of the elements in an array.
Parameters
Name | Description |
---|---|
array |
The input array. |
numberSelector |
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 ] }
sumBy(array: Null, numberSelector: (Nothing) -> Any): Null
Helper function that enables sumBy
to work with a null
value.
2.1.18. take
take<T>(array: Array<T>, n: Number): Array<T>
Selects the first n
elements. It returns an empty array when n <= 0
and the original array when n > sizeOf(array)
.
Parameters
Name | Description |
---|---|
array |
The array of elements. |
n |
The number of elements to select. |
Example
This example outputs an array that contains the values of first two elements of the input array.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
var users = ["Mariano", "Leandro", "Julian"]
output application/json
---
take(users, 2)
1
2
3
4
[
"Mariano",
"Leandro"
]
take(array: Null, n: Any): Null
Helper function that enables take
to work with a null
value.
2.1.19. takeWhile
takeWhile<T>(array: Array<T>, condition: (item: T) -> Boolean): Array<T>
Selects elements from the array while the condition is met but stops the selection process when it reaches an element that fails to satisfy the condition.
To select all elements that meet the condition, use the filter
function.
Parameters
Name | Description |
---|---|
array |
The array of elements. |
condition |
The condition (or expression) used to match an element in the array. |
Example
This example iterates over the elements in the array and selects only those
with an index that is <= 1
and stops selecting elements when it reaches
one that is greater than 2
. Notice that it does not select the second 1
because
of the 2
that precedes it in the array. The function outputs the result into an array.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,1]
---
arr takeWhile $ <= 1
1
2
3
4
[
0,
1
]
takeWhile(array: Null, condition: (item: Nothing) -> Any): Null
Helper function that enables takeWhile
to work with a null
value.
3. 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.
3.1. Functions
3.1.1. concatWith
concatWith(source: Binary, with: Binary): Binary
Concatenates the content of two binaries.
Parameters
Name | Type | Description |
---|---|---|
|
Binary |
The source binary content. |
|
Binary |
The binary to append. |
Example
This example concats two binaries into one binary.
1
2
3
4
5
%dw 2.0
import * from dw::core::Binaries
output application/dw
---
"CAFE" as Binary {base: "16"} concatWith "ABCD" as Binary {base: "16"}
1
"yv6rzQ==" as Binary {base: "64"}
concatWith(source: Binary, with: Null): Binary
Helper function that enables concatWith
to work with a null
value.
concatWith(source: Null, with: Binary): Binary
Helper function that enables concatWith
to work with a null
value.
3.1.2. fromBase64
fromBase64(base64String: String): Binary
Transforms a Base64 string into a binary value.
Parameters
Name | Description |
---|---|
base64String |
The Base64 string to transform. |
Example
This example takes a Base64 encoded string and transforms it into a binary value. This example assumes that the payload
contains the Base64 string generated from an image in example toBase64.
The output of this function is a binary value that represents the image generated in example toBase64.
1
2
3
4
5
%dw 2.0
import * from dw::core::Binaries
output application/octet-stream
---
fromBase64(payload)
3.1.3. fromHex
fromHex(hexString: String): Binary
Transforms a hexadecimal string into a binary.
Parameters
Name | Description |
---|---|
hexString |
A hexadecimal string to transform. |
Example
This example transforms a hexadecimal string to "Mule".
To make the resulting type clear, it outputs data in the application/dw
format.
1
2
3
4
5
%dw 2.0
import * from dw::core::Binaries
output application/dw
---
{ "hexToBinary": fromHex("4D756C65") }
1
2
3
{
hexToBinary: "TXVsZQ==" as Binary {base: "64"}
}
3.1.4. readLinesWith
readLinesWith(content: Binary, charset: String): Array<String>
Splits the specified binary content into lines and returns the results in an array.
Parameters
Name | Description |
---|---|
content |
Binary data to read and split. |
charset |
String representing the encoding to read. |
Example
This example transforms binary content, which is separated into new
lines (\n
), in a comma-separated array.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Binaries
var content = read("Line 1\nLine 2\nLine 3\nLine 4\nLine 5\n", "application/octet-stream")
output application/json
---
{
lines : (content readLinesWith "UTF-8"),
showType: typeOf(content)
}
1
2
3
4
{
"lines": [ "Line 1", "Line 2", "Line 3", "Line 4", "Line 5" ],
"showType": "Binary"
}
3.1.5. toBase64
toBase64(content: Binary): String
Transforms a binary value into a Base64 string.
Parameters
Name | Description |
---|---|
content |
The binary value to transform. |
Example
This example transforms a binary value into a Base64 encoded string. In this case, the binary value represents an image.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import dw::Crypto
import toBase64 from dw::core::Binaries
var emailChecksum = Crypto::MD5("achaval@gmail.com" as Binary)
var image = readUrl(log("https://www.gravatar.com/avatar/$(emailChecksum)"), "application/octet-stream")
output application/json
---
toBase64(image)
This example outputs a Base64 encoded string. The resulting string was shortened for readability purposes:
1
"/9j/4AAQSkZJRgABAQEAYABgAAD//..."
3.1.6. toHex
toHex(content: Binary): String
Transforms a binary value into a hexadecimal string.
Parameters
Name | Description |
---|---|
content |
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" }
3.1.7. writeLinesWith
writeLinesWith(content: Array<String>, charset: String): Binary
Writes the specified lines and returns the binary content.
Parameters
Name | Description |
---|---|
content |
Array of items to write. |
charset |
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"
}
4. dw::core::Dates
This module contains functions for creating and manipulating dates.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Dates
to the header of your
DataWeave script.
4.1. Functions
4.1.1. atBeginningOfDay
atBeginningOfDay(dateTime: DateTime): DateTime
Returns a new DateTime
value that changes the Time
value in the input to the
beginning of the specified day.
The hours, minutes, and seconds in the input change to 00:00:00
.
Parameters
Name | Description |
---|---|
dateTime |
The |
Example
This example changes the Time
value within the DateTime
input to the
beginning of the specified day.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
"atBeginningOfDayDateTime": atBeginningOfDay(|2020-10-06T18:23:20.351-03:00|)
}
1
2
3
{
"atBeginningOfDayDateTime": "2020-10-06T00:00:00-03:00"
}
atBeginningOfDay(localDateTime: LocalDateTime): LocalDateTime
Returns a new LocalDateTime
value that changes the Time
value within the
input to the start of the specified day.
The hours, minutes, and seconds in the input change to 00:00:00
.
Parameters
Name | Description |
---|---|
localDateTime |
The |
Example
This example changes the Time
value within the LocalDateTime
input to the
beginning of the specified day.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
"atBeginningOfDayLocalDateTime": atBeginningOfDay(|2020-10-06T18:23:20.351|)
}
1
2
3
{
"atBeginningOfDayLocalDateTime": "2020-10-06T00:00:00"
}
4.1.2. atBeginningOfHour
atBeginningOfHour(dateTime: DateTime): DateTime
Returns a new DateTime
value that changes the Time
value in the input to the
beginning of the specified hour.
The minutes and seconds in the input change to 00:00
.
Parameters
Name | Description |
---|---|
dateTime |
The |
Example
This example changes the Time
value within the DateTime
input to the
beginning of the specified hour.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
"atBeginningOfHourDateTime": atBeginningOfHour(|2020-10-06T18:23:20.351-03:00|)
}
1
2
3
{
"atBeginningOfHourDateTime": "2020-10-06T18:00:00-03:00"
}
atBeginningOfHour(localDateTime: LocalDateTime): LocalDateTime
Returns a new LocalDateTime
value that changes the Time
value in the input to the
beginning of the specified hour.
The minutes and seconds in the input change to 00:00
.
Parameters
Name | Description |
---|---|
localDateTime |
The |
Example
This example changes the Time
value within the LocalDateTime
input to the
beginning of the specified hour.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
"atBeginningOfHourLocalDateTime": atBeginningOfHour(|2020-10-06T18:23:20.351|)
}
1
2
3
{
"atBeginningOfHourLocalDateTime": "2020-10-06T18:00:00"
}
atBeginningOfHour(localTime: LocalTime): LocalTime
Returns a new LocalTime
value that changes its value in the input to the
beginning of the specified hour.
The minutes and seconds in the input change to 00:00
.
Parameters
Name | Description |
---|---|
localTime |
The |
Example
This example changes the LocalTime
value to the
beginning of the specified hour.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
"atBeginningOfHourLocalTime": atBeginningOfHour(|18:23:20.351|)
}
1
2
3
{
"atBeginningOfHourLocalTime": "18:00:00"
}
atBeginningOfHour(time: Time): Time
Returns a new Time
value that changes the input value to the
beginning of the specified hour.
The minutes and seconds in the input change to 00:00
.
Parameters
Name | Description |
---|---|
time |
The |
Example
This example changes the Time
value to the beginning of the specified hour.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
"atBeginningOfHourTime": atBeginningOfHour(|18:23:20.351-03:00|)
}
1
2
3
{
"atBeginningOfHourTime": "18:00:00-03:00"
}
4.1.3. atBeginningOfMonth
atBeginningOfMonth(dateTime: DateTime): DateTime
Returns a new DateTime
value that changes the Day
value from the
input to the first day of the specified month. It also sets the Time
value to 00:00:00
.
The day and time in the input changes to 01T00:00:00
.
Parameters
Name | Description |
---|---|
dateTime |
The |
Example
This example changes the Day
value within the DateTime
input to the
first day of the specified month and sets the Time
value to 00:00:00
.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
"atBeginningOfMonthDateTime": atBeginningOfMonth(|2020-10-06T18:23:20.351-03:00|)
}
1
2
3
{
"atBeginningOfMonthDateTime": "2020-10-01T00:00:00-03:00"
}
atBeginningOfMonth(localDateTime: LocalDateTime): LocalDateTime
Returns a new LocalDateTime
value that changes the Day
and LocalTime
values from the input to the beginning of the specified month.
The day and time in the input changes to 01T00:00:00
.
Parameters
Name | Description |
---|---|
localDateTime |
The |
Example
This example changes the Day
and LocalTime
values within the LocalDateTime
input to the beginning of the specified month.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
"atBeginningOfMonthLocalDateTime": atBeginningOfMonth(|2020-10-06T18:23:20.351|)
}
1
2
3
{
"atBeginningOfMonthLocalDateTime": "2020-10-01T00:00:00"
}
atBeginningOfMonth(date: Date): Date
Returns a new Date
value that changes the Day
value from the
input to the first day of the specified month.
The day in the input changes to 01
.
Parameters
Name | Description |
---|---|
date |
The |
Example
This example changes the Day
value within the Date
input to the first day of the specified month.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
atBeginningOfMonthDate: atBeginningOfMonth(|2020-10-06|)
}
1
2
3
{
"atBeginningOfMonthDate": "2020-10-01"
}
4.1.4. atBeginningOfWeek
atBeginningOfWeek(dateTime: DateTime): DateTime
Returns a new DateTime
value that changes the Day
and Time
values from the
input to the beginning of the first day of the specified week.
The function treats Sunday as the first day of the week.
Parameters
Name | Description |
---|---|
dateTime |
The |
Example
This example changes the Day
and Time
values (06T18:23:20.351
) within
the DateTime
input to the beginning of the first day of the specified week
(04T00:00:00
).
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
atBeginningOfWeekDateTime: atBeginningOfWeek(|2020-10-06T18:23:20.351-03:00|)
}
1
2
3
{
"atBeginningOfWeekDateTime": "2020-10-04T00:00:00-03:00"
}
atBeginningOfWeek(localDateTime: LocalDateTime): LocalDateTime
Returns a new LocalDateTime
value that changes the Day
and Time
values from the
input to the beginning of the first day of the specified week.
The function treats Sunday as the first day of the week.
Parameters
Name | Description |
---|---|
localDateTime |
The |
Example
This example changes the Day
and Time
values (06T18:23:20.351
) within
the LocalDateTime
input to the beginning of the first day of the specified week
(04T00:00:00
).
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
atBeginningOfWeekLocalDateTime: atBeginningOfWeek(|2020-10-06T18:23:20.351|)
}
1
2
3
{
"atBeginningOfWeekLocalDateTime": "2020-10-04T00:00:00"
}
atBeginningOfWeek(date: Date): Date
Returns a new Date
value that changes the Date
input
input to the first day of the specified week.
The function treats Sunday as the first day of the week.
Parameters
Name | Description |
---|---|
date |
The |
Example
This example changes the Day
value (06
) within
the Date
input to the first day of the week that contains 2020-10-06
(a Tuesday), which is 2020-10-04
(a Sunday).
The Day
value changes from 06
to 04
.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
atBeginningOfWeekDate: atBeginningOfWeek(|2020-10-06|)
}
1
2
3
{
"atBeginningOfWeekDate": "2020-10-04"
}
4.1.5. atBeginningOfYear
atBeginningOfYear(dateTime: DateTime): DateTime
Takes a DateTime
value as input and returns a DateTime
value for
the first day of the year specified in the input. It also sets the Time
value to 00:00:00
.
The month, day, and time in the input changes to 01-01T00:00:00
.
Parameters
Name | Description |
---|---|
dateTime |
The |
Example
This example transforms the DateTime
input (|2020-10-06T18:23:20.351-03:00|
)
to the date of the first day of the Year
value (2020
) in the input.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
atBeginningOfYearDateTime: atBeginningOfYear(|2020-10-06T18:23:20.351-03:00|)
}
1
2
3
{
"atBeginningOfYearDateTime": "2020-01-01T00:00:00.000-03:00"
}
atBeginningOfYear(localDateTime: LocalDateTime): LocalDateTime
Takes a LocalDateTime
value as input and returns a LocalDateTime
value for
the first day of the year specified in the input. It also sets the Time
value to 00:00:00
.
The month, day, and time in the input changes to 01-01T00:00:00
.
Parameters
Name | Description |
---|---|
localDateTime |
The |
Example
This example transforms the LocalDateTime
input (|2020-10-06T18:23:20.351|
)
to the date of the first day of the Year
value (2020
) in the input.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
atBeginningOfYearLocalDateTime: atBeginningOfYear(|2020-10-06T18:23:20.351|)
}
1
2
3
{
"atBeginningOfYearLocalDateTime": "2020-01-01T00:00:00"
}
atBeginningOfYear(date: Date): Date
Takes a Date
value as input and returns a Date
value for
the first day of the year specified in the input.
The month and day in the input changes to 01-01
.
Parameters
Name | Description |
---|---|
date |
The |
Example
This example transforms Date
input (|2020-10-06|
) to the date of the
first day of the Year
value (2020
) in the input.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
atBeginningOfYearDate: atBeginningOfYear(|2020-10-06|)
}
1
2
3
{
"atBeginningOfYearDate": "2020-01-01"
}
4.1.6. date
date(parts: DateFactory): Date
Creates a Date
value from values specified for year
, month
, and day
fields.
Parameters
Name | Description |
---|---|
parts |
|
Example
This example shows how to create a value of type Date
.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
newDate: date({year: 2012, month: 10, day: 11})
}
1
2
3
{
"newDate": "2012-10-11"
}
4.1.7. dateTime
dateTime(parts: DateTimeFactory): DateTime
Creates a DateTime
value from values specified for year
, month
, day
, hour
,
minutes
, seconds
, and timezone
fields.
Parameters
Name | Description |
---|---|
parts |
|
Example
This example shows how to create a value of type DateTime
.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
newDateTime: dateTime({year: 2012, month: 10, day: 11, hour: 12, minutes: 30, seconds: 40 , timeZone: |-03:00|})
}
1
2
3
{
"newDateTime": "2012-10-11T12:30:40-03:00"
}
4.1.8. localDateTime
localDateTime(parts: LocalDateTimeFactory): LocalDateTime
Creates a LocalDateTime
value from values specified for year
, month
, day
,
hour
, minutes
, and seconds
fields.
Parameters
Name | Description |
---|---|
parts |
|
Example
This example shows how to create a value of type LocalDateTime
.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
newLocalDateTime: localDateTime({year: 2012, month: 10, day: 11, hour: 12, minutes: 30, seconds: 40})
}
1
2
3
{
"newLocalDateTime": "2012-10-11T12:30:40"
}
4.1.9. localTime
localTime(parts: LocalTimeFactory): LocalTime
Creates a LocalTime
value from values specified for hour
, minutes
, and
seconds
fields.
Parameters
Name | Description |
---|---|
parts |
|
Example
This example shows how to create a value of type LocalTime
.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
newLocalTime: localTime({ hour: 12, minutes: 30, seconds: 40})
}
1
2
3
{
"newLocalTime": "12:30:40"
}
4.1.10. time
time(parts: TimeFactory): Time
Creates a Time
value from values specified for hour
, minutes
, seconds
, and
timezone
fields.
Parameters
Name | Description |
---|---|
parts |
|
Example
This example shows how to create a value of type Time
.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::Dates
output application/json
---
{
newTime: time({ hour: 12, minutes: 30, seconds: 40 , timeZone: |-03:00| })
}
1
2
3
{
"newTime": "12:30:40-03:00"
}
4.1.11. today
today(): Date
Returns the date for today as a Date
type.
Example
This example shows the output of today
function.
1
2
3
4
5
%dw 2.0
import * from dw::core::Dates
output application/json
---
today()
1
"2021-05-15"
4.1.12. tomorrow
tomorrow(): Date
Returns the date for tomorrow as a Date
type.
Example
This example shows the output of tomorrow
function.
1
2
3
4
5
%dw 2.0
import tomorrow from dw::core::Dates
output application/json
---
tomorrow()
1
"2021-05-16"
4.1.13. yesterday
yesterday(): Date
Returns the date for yesterday as a Date
type.
Example
This example shows the output of yesterday
function.
1
2
3
4
5
%dw 2.0
import * from dw::core::Dates
output application/json
---
yesterday()
1
"2021-05-14"
4.2. Types
4.2.1. DateFactory
Type containing selectable day
, month
, and year
keys and
corresponding Number
values, such as {day: 21, month: 1, year: 2021}
.
The fields accept a Number
value. Numbers preceded by 0
, such as 01
,
are not valid.
1
{ day: Number, month: Number, year: Number }
4.2.2. DateTimeFactory
Type that combines DateFactory
, LocalTimeFactory
, and Zoned
types. For example,
{day: 21, month: 1, year: 2021, hour: 8, minutes: 31, seconds: 55, timeZone : |-03:00|} as DateTimeFactory
is a valid DateTimeFactory
value.
1
DateFactory & LocalTimeFactory & Zoned
4.2.3. LocalDateTimeFactory
Type that combines DateFactory
and LocalTimeFactory
types. For example,
{day: 21, month: 1, year: 2021, hour: 8, minutes: 31, seconds: 55, timeZone : |-03:00|} as LocalDateTimeFactory
is a valid LocalDateTimeFactory
value. The timeZone
field is optional.
1
DateFactory & LocalTimeFactory
4.2.4. LocalTimeFactory
Type containing selectable hour
, minutes
, and seconds
keys and
corresponding Number
values, such as {hour: 8, minutes: 31, seconds: 55}
.
The fields accept any Number
value.
1
{ hour: Number, minutes: Number, seconds: Number }
4.2.5. TimeFactory
Type that combines LocalTimeFactory
and Zoned
types. For example,
{hour: 8, minutes: 31, seconds: 55, timeZone : |-03:00|} as TimeFactory
is a valid TimeFactory
value.
1
LocalTimeFactory & Zoned
4.2.6. Zoned
Type containing a selectable timeZone
key and TimeZone
value, such as
{ timezone : |-03:00|}
.
1
{ timeZone: TimeZone }
5. dw::core::Numbers
This module contains helper functions for working with numbers.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Numbers
to the header of your
DataWeave script.
5.1. Functions
5.1.1. fromBinary
fromBinary(binaryText: String): Number
Transforms from a binary number into a decimal number.
Parameters
Name | Description |
---|---|
binaryText |
The binary number represented in a |
Example
This example shows how the toBinary
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import fromBinary from dw::core::Numbers
output application/json
---
{
a: fromBinary("-10"),
b: fromBinary("11111000111010111010110100101011100001001110000011010101100010111101001011100000100010011000011101100101101001111101111010110010010100110010100100000000000000000000000000000000000000000000000000000000000000"),
c: fromBinary(0),
d: fromBinary(null),
e: fromBinary("100"),
}
1
2
3
4
5
6
7
{
"a": -2,
"b": 100000000000000000000000000000000000000000000000000000000000000,
"c": 0,
"d": null,
"e": 4
}
fromBinary(binaryText: Null): Null
Helper function that enables fromBinary
to work with null value.
5.1.2. fromHex
fromHex(hexText: String): Number
Transforms a hexadecimal number into decimal number.
Parameters
Name | Description |
---|---|
hexText |
The hexadecimal number represented in a |
Example
This example shows how the toBinary
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import fromHex from dw::core::Numbers
output application/json
---
{
a: fromHex("-1"),
b: fromHex("3e3aeb4ae1383562f4b82261d969f7ac94ca4000000000000000"),
c: fromHex(0),
d: fromHex(null),
e: fromHex("f"),
}
1
2
3
4
5
6
7
{
"a": -1,
"b": 100000000000000000000000000000000000000000000000000000000000000,
"c": 0,
"d": null,
"e": 15
}
fromHex(hexText: Null): Null
Helper function that enables fromHex
to work with null value.
5.1.3. fromRadixNumber
fromRadixNumber(numberStr: String, radix: Number): Number
Transforms a number in the specified radix into decimal number
Parameters
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
8
%dw 2.0
import fromRadixNumber from dw::core::Numbers
output application/json
---
{
a: fromRadixNumber("10", 2),
b: fromRadixNumber("FF", 16)
}
1
2
3
4
{
"a": 2,
"b": 255
}
5.1.4. toBinary
toBinary(number: Number): String
Transforms a decimal number into a binary number.
Parameters
Name | Description |
---|---|
number |
The input number. |
Example
This example shows how the toBinary
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import toBinary from dw::core::Numbers
output application/json
---
{
a: toBinary(-2),
b: toBinary(100000000000000000000000000000000000000000000000000000000000000),
c: toBinary(0),
d: toBinary(null),
e: toBinary(2),
}
1
2
3
4
5
6
7
{
"a": "-10",
"b": "11111000111010111010110100101011100001001110000011010101100010111101001011100000100010011000011101100101101001111101111010110010010100110010100100000000000000000000000000000000000000000000000000000000000000",
"c": "0",
"d": null,
"e": "10"
}
toBinary(number: Null): Null
Helper function that enables toBinary
to work with null value.
5.1.5. toHex
toHex(number: Number): String
Transforms a decimal number into a hexadecimal number.
Parameters
Name | Description |
---|---|
number |
The input number. |
Example
This example shows how toHex
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import toHex from dw::core::Numbers
output application/json
---
{
a: toHex(-1),
b: toHex(100000000000000000000000000000000000000000000000000000000000000),
c: toHex(0),
d: toHex(null),
e: toHex(15),
}
1
2
3
4
5
6
7
{
"a": "-1",
"b": "3e3aeb4ae1383562f4b82261d969f7ac94ca4000000000000000",
"c": "0",
"d": null,
"e": "f"
}
toHex(number: Null): Null
Helper function that enables toHex
to work with null value.
5.1.6. toRadixNumber
toRadixNumber(number: Number, radix: Number): String
Transforms a decimal number into a number string in other radix.
Parameters
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
8
%dw 2.0
import toRadixNumber from dw::core::Numbers
output application/json
---
{
a: toRadixNumber(2, 2),
b: toRadixNumber(255, 16)
}
1
2
3
4
{
"a": "10",
"b": "ff"
}
6. dw::core::Objects
This module contains helper functions for working 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.
6.1. Functions
6.1.1. divideBy
divideBy(items: Object, amount: 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 |
---|---|
items |
Key-value pairs in the source object. |
amount |
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
}
]
}
6.1.2. entrySet
entrySet<T <: Object>(obj: T): Array<{| key: Key, value: Any, attributes: Object |}>
Returns an array of key-value pairs that describe the key, value, and any attributes in the input object.
Parameters
Name | Description |
---|---|
obj |
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"
}
}
]
}
6.1.3. everyEntry
everyEntry(object: Object, condition: (value: Any, key: Key) -> Boolean): Boolean
Returns true
if every entry in the object matches the condition.
The function stops iterating after the first negative evaluation of an element in the object.
Parameters
Name | Description |
---|---|
object |
The object to evaluate. |
condition |
The condition to apply to each element. |
Example
This example shows how everyEntry
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import everyEntry from dw::core::Objects
output application/json
---
{
a: {} everyEntry (value, key) -> value is String,
b: {a: "", b: "123"} everyEntry (value, key) -> value is String,
c: {a: "", b: 123} everyEntry (value, key) -> value is String,
d: {a: "", b: 123} everyEntry (value, key) -> key as String == "a",
e: {a: ""} everyEntry (value, key) -> key as String == "a",
f: null everyEntry ((value, key) -> key as String == "a")
}
1
2
3
4
5
6
7
8
{
"a": true,
"b": true,
"c": false,
"d": false,
"e": true,
"f": true
}
everyEntry(list: Null, condition: (Nothing, Nothing) -> Boolean): Boolean
Helper function that enables everyEntry
to work with a null
value.
6.1.4. keySet
keySet<K, V>(obj: { (K)?: V }): Array<K>
Returns an array of key names from an object.
Parameters
Name | Description |
---|---|
object |
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
]
}
6.1.5. mergeWith
mergeWith<T <: Object, V <: Object>(source: T, target: 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 |
---|---|
source |
The object to append to the |
target |
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<T <: Object>(a: Null, b: T): T
Helper function that enables mergeWith
to work with a null
value.
mergeWith<T <: Object>(a: T, b: Null): T
Helper function that enables mergeWith
to work with a null
value.
6.1.6. nameSet
nameSet(obj: Object): Array<String>
Returns an array of keys from an object.
Parameters
Name | Description |
---|---|
obj |
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"] }
6.1.7. someEntry
someEntry(obj: Object, condition: (value: Any, key: Key) -> Boolean): Boolean
Returns true
if at least one entry in the object matches the specified condition.
The function stops iterating after the first element that matches the condition is found.
Parameters
Name | Description |
---|---|
obj |
The object to evaluate. |
condition |
The condition to use when evaluating elements in the object. |
Example
This example shows how the someEntry
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import someEntry from dw::core::Objects
output application/json
---
{
a: {} someEntry (value, key) -> value is String,
b: {a: "", b: "123"} someEntry (value, key) -> value is String,
c: {a: "", b: 123} someEntry (value, key) -> value is String,
d: {a: "", b: 123} someEntry (value, key) -> key as String == "a",
e: {a: ""} someEntry (value, key) -> key as String == "b",
f: null someEntry (value, key) -> key as String == "a"
}
1
2
3
4
5
6
7
8
{
"a": false,
"b": true,
"c": true,
"d": true,
"e": false,
"f": false
}
someEntry(obj: Null, condition: (value: Nothing, key: Nothing) -> Boolean): Boolean
Helper function that enables someEntry
to work with a null
value.
6.1.8. takeWhile
takeWhile<T>(obj: Object, condition: (value: Any, key: Key) -> Boolean): Object
Selects key-value pairs from the object while the condition is met.
Parameters
Name | Description |
---|---|
obj |
The object to filter. |
condition |
The condition (or expression) used to match a key-value pairs in the object. |
Example
This example iterates over the key-value pairs in the object and selects the elements while the condition is met. It outputs the result into an object.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Objects
output application/json
var obj = {
"a": 1,
"b": 2,
"c": 5,
"d": 1
}
---
obj takeWhile ((value, key) -> value < 3)
1
2
3
4
{
"a": 1,
"b": 2
}
6.1.9. valueSet
valueSet<K, V>(obj: { (K)?: V }): Array<V>
Returns an array of the values from key-value pairs in an object.
Parameters
Name | Description |
---|---|
obj |
The object to evaluate. |
Example
This example returns the values from the input object.
1
2
3
4
5
%dw 2.0
import * from dw::core::Objects
output application/json
---
{ "valueSet" : valueSet({a: true, b: 1}) }
1
{ "valueSet" : [true,1] }
7. dw::core::Periods
This module contains functions for working with and creating Period values.
To use this module, you must import it to your DataWeave code,
for example, by adding the line import * from dw::core::Periods
to the header of your DataWeave script.
7.1. Functions
7.1.1. between
between(endDateExclusive: Date, startDateInclusive: Date): Period
Returns a Period (P) value consisting of the number of years, months, and days between two Date values.
The start date is included, but the end date is not.
The result of this method can be a negative period
if the end date (endDateExclusive
) is before the
start date (startDateInclusive
).
Note that the first parameter of the function is the endDateExclusive
and the second one is the startDateInclusive
.
Parameters
Name | Description |
---|---|
endDateExclusive |
The end date, exclusive. |
startDateInclusive |
The start date, inclusive. |
Example
This example shows how between
behaves with different inputs.
1
2
3
4
5
6
7
8
import * from dw::core::Periods
output application/json
---
{
a: between(|2010-12-12|,|2010-12-10|),
b: between(|2011-12-11|,|2010-11-10|),
c: between(|2020-02-29|,|2020-03-30|)
}
1
2
3
4
5
{
"a": "P2D",
"b": "P1Y1M1D",
"c": "P-1M-1D"
}
7.1.2. days
days(nDays: Number): Period
Creates a Period value from the provided number of days.
The function applies the period
function to input that is a whole number
and the duration
function to decimal input.
Parameters
Name | Description |
---|---|
nDays |
The number of hours as a whole or decimal number. A positive or negative number is valid. |
Example
This example shows how days
behaves with different inputs. It
adds and subtracts hours from DateTime values. It also converts the
decimal value 4.555
into a number of hours, minutes, and second in
the Period format (PT109H19M12S
) and the whole number 4
into a
number of days in the Period format (P4D
).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import * from dw::core::Periods
output application/json
---
{
tomorrow: |2020-10-05T20:22:34.385Z| + days(1),
yesterday: |2020-10-05T20:22:34.385Z| - days(1),
decimalDaysPlusQuarter: |2020-10-05T00:00:00.000Z| + days(0.25),
decimalDaysPlusHalf: |2020-10-05T00:00:00.000Z| + days(0.5),
decimalDaysPlusThreeQuarters: |2020-10-05T00:00:00.000Z| + days(0.75),
decimalInputAsPeriod : days(4.555),
fourDayPeriod: days(4),
negativeValue: days(-1)
}
1
2
3
4
5
6
7
8
9
10
{
"tomorrow": "2020-10-06T20:22:34.385Z",
"yesterday": "2020-10-04T20:22:34.385Z",
"decimalDaysPlusQuarter": "2020-10-05T06:00:00Z",
"decimalDaysPlusHalf": "2020-10-05T12:00:00Z",
"decimalDaysPlusThreeQuarters": "2020-10-05T18:00:00Z",
"decimalInputAsPeriod": "PT109H19M12S",
"fourDayPeriod": "P4D",
"negativeValue": "P-1D"
}
7.1.3. duration
duration(period: { days?: Number, hours?: Number, minutes?: Number, seconds?: Number }): Period
Creates a Period value that represents a number of days, hours, minutes, or seconds.
Parameters
Name | Description |
---|---|
period |
An object such as |
Example
This example shows how duration
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import * from dw::core::Periods
output application/json
---
{
dayAfterDateTime: |2020-10-05T20:22:34.385Z| + duration({days: 1}),
dayAndHourBeforeDateTime: |2020-10-05T20:22:34.385Z| - duration({days: 1, hours: 1}),
pointInTimeBefore: |2020-10-05T20:22:34.385Z| - duration({days: 1, hours: 1, minutes: 20, seconds: 10}),
emptyDuration: duration({}),
constructDuration: duration({days:4, hours:11, minutes:28}),
selectHoursFromDuration: duration({days:4, hours:11, minutes:28}).hours,
decimalAsPeriod: duration({seconds: 30.5}),
addNegativeValue: duration({ minutes : 1 }) + duration({ seconds : -1 })
}
1
2
3
4
5
6
7
8
9
10
{
"dayAfterDateTime": "2020-10-06T20:22:34.385Z",
"dayAndHourBeforeDateTime": "2020-10-04T19:22:34.385Z",
"pointInTimeBefore": "2020-10-04T19:02:24.385Z",
"emptyDuration": "PT0S",
"constructDuration": "PT107H28M",
"selectHoursFromDuration": 11,
"decimalAsPeriod": "PT30.5S",
"addNegativeValue": 59
}
7.1.4. hours
hours(nHours: Number): Period
Creates a Period value from the provided number of hours.
The function applies the duration
function to the input value.
Parameters
Name | Description |
---|---|
nHours |
The number of hours as a whole or decimal number. A positive or negative number is valid. |
Example
This example shows how hours
behaves with different inputs.
It adds and subtracts hours from DateTime and LocalTime values.
It also converts the decimal value 4.555
into the Period format
(PT4H33M18S
) and the whole number 4
into the Period format (PT4H
).
Notice that hours(-1) + hours(2)
returns the number of seconds.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
import * from dw::core::Periods
output application/json
---
{
nextHour: |2020-10-05T20:22:34.385Z| + hours(1),
previousHour: |2020-10-05T20:22:34.385Z| - hours(1),
threeHoursLater: |20:22| + hours(3),
addDecimalInput: |20:22| + hours(3.5),
decimalInputAsPeriod : hours(4.555),
fourHourPeriod : hours(4),
addNegativeValue: hours(-1) + hours(2)
}
1
2
3
4
5
6
7
8
9
{
"nextHour": "2020-10-05T21:22:34.385Z",
"previousHour": "2020-10-05T19:22:34.385Z",
"threeHoursLater": "23:22:00",
"addDecimalInput": "23:52:00",
"decimalInputAsPeriod": "PT4H33M18S",
"fourHourPeriod": "PT4H",
"addNegativeValue": 3600
}
7.1.5. minutes
minutes(nMinutes: Number): Period
Creates a Period value from the provided number of minutes.
The function applies the duration
function to the input value.
Parameters
Name | Description |
---|---|
nMinutes |
The number of minutes as a whole or decimal number. A positive or negative number is valid. |
Example
This example shows how minutes
behaves with different inputs.
It adds and subtracts hours from DateTime values. It also converts
the decimal value 4.555
into the Period format (PT4M33.3S
) and
and the whole number 4
into the Period format (PT4M
). Notice
that minutes(-1) + minutes(2)
returns the number of seconds.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Periods
output application/json
---
{
nextMinute: |2020-10-05T20:22:34.385Z| + minutes(1),
previousMinute: |2020-10-05T20:22:34.385Z| - minutes(1),
decimalInputPeriod: minutes(4.555),
wholeNumberInputPeriod: minutes(4),
addNegativeValue: minutes(-1) + minutes(2)
}
1
2
3
4
5
6
7
{
"nextMinute": "2020-10-05T20:23:34.385Z",
"previousMinute": "2020-10-05T20:21:34.385Z",
"decimalInputPeriod": "PT4M33.3S",
"wholeNumberInputPeriod": "PT4M",
"addNegativeValue": 60
}
7.1.6. months
months(nMonths: Number): Period
Creates a Period value from the provided number of months.
The function applies the period
function to the input value.
Parameters
Name | Description |
---|---|
nMonths |
The number of months as a whole number. A positive or negative number is valid. |
Example
This example shows how months
behaves with different inputs.
It adds a month to a DateTime value, and it converts the
whole number 4
to a number of months in the Period format (P4M
).
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Periods
output application/json
---
{
nextMonth: |2020-10-05T20:22:34.385Z| + months(1),
fourMonthPeriod : months(4),
addNegativeValue: months(-1) + months(2)
}
1
2
3
4
5
{
"nextMonth": "2020-11-05T20:22:34.385Z",
"fourMonthPeriod": "P4M",
"addNegativeValue": 1
}
7.1.7. period
period(period: { years?: Number, months?: Number, days?: Number }): Period
Creates a Period value as a date-based number of years, months, and days in the ISO-8601 calendar system.
Parameters
Name | Description |
---|---|
period |
An object such as |
Example
This example shows how period
behaves with different inputs. The example
add a subtracts and adds the result of a period
function to DateTime and
Date values. It also constructs a Period value from period
objects
and selects a months
value from the object.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
output application/json
import * from dw::core::Periods
---
{
dayBeforeDateTime: |2020-10-05T20:22:34.385Z| - period({days:1}),
dayAfterDate: |2020-10-05| + period({days:1}),
yearMonthDayAfterDate: |2020-10-05| + period({years:1, months:1, days:1}),
emptyPeriod: period({}),
constructPeriod: period({years:4, months:11, days:28}),
selectMonthsFromPeriod: period({years:4, months:11, days:28}).months
}
1
2
3
4
5
6
7
8
{
"dayBeforeDateTime": "2020-10-04T20:22:34.385Z",
"dayAfterDate": "2020-10-06",
"yearMonthDayAfterDate": "2021-11-06",
"emptyPeriod": "P0D",
"constructPeriod": "P4Y11M28D",
"selectMonthsFromPeriod": 11
}
7.1.8. seconds
seconds(nSecs: Number): Period
Creates a Period value from the provided number of seconds.
Parameters
Name | Description |
---|---|
nSecs |
The number of seconds as a whole or decimal number. A positive or negative number is valid. |
Example
This example shows how seconds
behaves with different inputs.
It adds and subtracts seconds from DateTime values. It also converts
the decimal value 4.555
into the Period format (PT4.555S
) and
and the whole number 4
into the Period format (PT4S
)
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Periods
output application/json
---
{
nextSecond: |2020-10-05T20:22:34.385Z| + seconds(1),
previousSecond: |2020-10-05T20:22:34.385Z| - seconds(1),
decimalInputPeriod: seconds(4.555),
wholeNumberInputPeriod: seconds(4),
addNegativeValue: seconds(-1) + seconds(2)
}
1
2
3
4
5
6
7
{
"nextSecond": "2020-10-05T20:22:35.385Z",
"previousSecond": "2020-10-05T20:22:33.385Z",
"decimalInputPeriod": "PT4.555S",
"wholeNumberInputPeriod": "PT4S",
"addNegativeValue": 1
}
7.1.9. years
years(nYears: Number): Period
Creates a Period value from the provided number of years.
The function applies the period
function to the input value.
Parameters
Name | Description |
---|---|
nYears |
A whole number for the number of years. A positive or negative number is valid. |
Example
This example shows how years
behaves with different inputs.
It adds a year to a DateTime value, and it converts the whole
number 4 into a number of years in the Period format (P4Y
).
Notice that years(-1) + years(2)
returns the number of months.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Periods
output application/json
---
{
nextYear: |2020-10-05T20:22:34.385Z| + years(1),
fourYearPeriod: years(4),
addNegativeValue: years(-1) + years(2)
}
1
2
3
4
5
{
"nextYear": "2021-10-05T20:22:34.385Z",
"fourYearPeriod": "P4Y",
"addNegativeValue": 12
}
8. dw::core::Strings
This module contains helper functions for working 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.
8.1. Functions
8.1.1. appendIfMissing
appendIfMissing(text: String, suffix: String): String
Appends the suffix
to the end of the text
if the text
does not already
ends with the suffix
.
Parameters
Name | Description |
---|---|
text |
The input string. |
suffix |
The text used as the suffix. |
Example
This example shows how appendIfMissing
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import appendIfMissing from dw::core::Strings
output application/json
---
{
"a": appendIfMissing(null, ""),
"b": appendIfMissing("abc", ""),
"c": appendIfMissing("", "xyz") ,
"d": appendIfMissing("abc", "xyz") ,
"e": appendIfMissing("abcxyz", "xyz")
}
1
2
3
4
5
6
7
{
"a": null,
"b": "abc",
"c": "xyz",
"d": "abcxyz",
"e": "abcxyz"
}
appendIfMissing(text: Null, suffix: String): Null
Helper function that enables appendIfMissing
to work with a null
value.
8.1.2. camelize
camelize(text: String): String
Returns a string in camel case based on underscores in the string.
All underscores are deleted, including any underscores at the beginning of the string.
Parameters
Name | Description |
---|---|
text |
The string to convert to camel case. |
Example
This example converts a string that contains underscores to camel case.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a" : camelize("customer_first_name"),
"b" : camelize("_name_starts_with_underscore")
}
1
2
3
4
{
"a": "customerFirstName",
"b": "nameStartsWithUnderscore"
}
camelize(text: Null): Null
Helper function that enables camelize
to work with a null
value.
8.1.3. capitalize
capitalize(text: 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 |
---|---|
text |
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(text: Null): Null
Helper function that enables capitalize
to work with a null
value.
8.1.4. charCode
charCode(text: 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 |
---|---|
text |
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 }
charCode(text: Null): Null
Helper function that enables charCode
to work with a null
value.
8.1.5. charCodeAt
charCodeAt(content: String, position: Number): Number
Returns the Unicode for a character at the specified index.
This function fails if the index is invalid.
Parameters
Name | Description |
---|---|
content |
The input string. |
position |
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 }
charCodeAt(content: Null, position: Any): Null
Helper function that enables charCodeAt
to work with a null
value.
8.1.6. collapse
collapse(text: String): Array<String>
Collapses the string into substrings of equal characters.
Each substring contains a single character or identical characters that are adjacent to one another in the input string. Empty spaces are treated as characters.
Parameters
Name | Description |
---|---|
text |
The string to collapse. |
Example
This example shows how the function collapses characters. Notice that the empty space (" ") is treated as a character.
1
2
3
4
5
%dw 2.0
import collapse from dw::core::Strings
output application/json
---
collapse("a b babb a")
1
["a", " ", "b", " ", "b", "a", "bb", " ", "a"]
collapse(text: Null): Null
Helper function that enables collapse
to work with a null
value.
8.1.7. countCharactersBy
countCharactersBy(text: String, predicate: (character: String) -> Boolean): Number
Counts the number of times an expression that iterates through
each character in a string returns true
.
Parameters
Name | Description |
---|---|
text |
The string to which the |
predicate |
Expression to apply to each character in the
|
Example
This example counts the digits in a string.
1
2
3
4
5
%dw 2.0
import * from dw::core::Strings
output application/json
---
"42 = 11 * 2 + 20" countCharactersBy isNumeric($)
1
7
countCharactersBy(text: Null, predicate: (character: Nothing) -> Any): Null
Helper function to make countCharactersBy
work with a null
value.
8.1.8. countMatches
countMatches(text: String, pattern: String): Number
Counts the number of matches in a string.
Parameters
Name | Description |
---|---|
text |
The string to search for matches. |
pattern |
A substring to find in the text. |
Example
This example counts matches in a string.
1
2
3
4
5
%dw 2.0
import countMatches from dw::core::Strings
output application/json
---
"hello worlo!" countMatches "lo"
1
2
countMatches(text: String, pattern: Regex): Number
Counts the number of times a regular expression matches text in a string.
Parameters
Name | Description |
---|---|
text |
The string to search for matches. |
pattern |
The regex pattern to use in the search. |
Example
This example counts the vowels in a string.
1
2
3
4
5
%dw 2.0
import countMatches from dw::core::Strings
output application/json
---
"hello, ciao!" countMatches /[aeiou]/
1
5
countMatches(text: Null, pattern: Any): Null
Helper function that enables countMatches
to work with a null
value.
8.1.9. dasherize
dasherize(text: 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 |
---|---|
text |
The input string. |
Example
This example replaces the spaces, underscores, and camel-casing in the input. Notice that the input "customer" is not modified in the output.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a" : dasherize("customer"),
"b" : dasherize("customer_first_name"),
"c" : dasherize("customer NAME"),
"d" : dasherize("customerName")
}
1
2
3
4
5
6
{
"a": "customer",
"b": "customer-first-name",
"c": "customer-name",
"d": "customer-name"
}
dasherize(text: Null): Null
Helper function that enables dasherize
to work with a null
value.
8.1.10. everyCharacter
everyCharacter(text: String, condition: (character: String) -> Boolean): Boolean
Checks whether a condition is valid for every character in a string.
Parameters
Name | Description |
---|---|
text |
The string to check. |
condition |
Expression that iterates through the characters in the string that it checks and returns a Boolean value. |
Example
This example determines whether a string is composed of only digits and spaces.
1
2
3
4
5
%dw 2.0
import * from dw::core::Strings
output application/json
---
"12 34 56" everyCharacter $ == " " or isNumeric($)
1
true
everyCharacter(text: Null, condition: (character: Nothing) -> Any): true
Helper function that enables everyCharacter
to work with a null
value.
8.1.11. first
first(text: String, amount: Number): String
Returns characters from the beginning of a string to the specified number of characters in the string, for example, the first two characters of a string.
If the number is equal to or greater than the number of characters in the string, the function returns the entire string.
Parameters
Name | Description |
---|---|
text |
The string to process. |
amount |
The number of characters to return. Negative
numbers and |
Example
This example returns the first five characters from a string.
1
2
3
4
5
%dw 2.0
import first from dw::core::Strings
output application/json
---
"hello world!" first 5
1
"hello"
first(text: Null, amount: Any): Null
Helper function that enables first
to work with a null
value.
8.1.12. fromCharCode
fromCharCode(charCode: Number): String
Returns a character that matches the specified Unicode.
Parameters
Name | Description |
---|---|
charCode |
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" }
fromCharCode(charCode: Null): Null
Helper function that enables fromCharCode
to work with a null
value.
8.1.13. hammingDistance
hammingDistance(a: String, b: String): Number | Null
Returns the Hamming distance between two strings.
Parameters
Name | Description |
---|---|
a |
The first string. |
b |
The second string. |
Example
This example shows how hammingDistance
behaves with different strings.
1
2
3
4
5
%dw 2.0
import hammingDistance from dw::core::Strings
output application/json
---
"holu" hammingDistance "chau"
1
3
8.1.14. isAlpha
isAlpha(text: 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.
Parameters
Name | Description |
---|---|
text |
The input string. |
Example
This example shows how isAlpha
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import isAlpha from dw::core::Strings
output application/json
---
{
"a": isAlpha(null),
"b": isAlpha(""),
"c": isAlpha(" "),
"d": isAlpha("abc"),
"e": isAlpha("ab2c"),
"f": isAlpha("ab-c")
}
1
2
3
4
5
6
7
8
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": false
}
isAlpha(text: Null): Boolean
Helper function that enables isAlpha
to work with a null
value.
8.1.15. isAlphanumeric
isAlphanumeric(text: String): Boolean
Checks if the text
contains only Unicode letters or digits.
Parameters
Name | Description |
---|---|
text |
The input string. |
Example
This example shows how isAlphanumeric
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
import isAlphanumeric from dw::core::Strings
output application/json
---
{
"a": isAlphanumeric(null),
"b": isAlphanumeric(""),
"c": isAlphanumeric(" "),
"d": isAlphanumeric("abc"),
"e": isAlphanumeric("ab c"),
"f": isAlphanumeric("ab2c"),
"g": isAlphanumeric("ab-c")
}
1
2
3
4
5
6
7
8
9
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": true,
"g": false
}
isAlphanumeric(text: Null): Boolean
Helper function that enables isAlphanumeric
to work with a null
value.
8.1.16. isLowerCase
isLowerCase(text: String): Boolean
Checks if the text
contains only lowercase characters.
Parameters
Name | Description |
---|---|
text |
The input string. |
Example
This example shows how isLowerCase
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import isLowerCase from dw::core::Strings
output application/json
---
{
"a": isLowerCase(null),
"b": isLowerCase(""),
"c": isLowerCase(" "),
"d": isLowerCase("abc"),
"e": isLowerCase("aBC"),
"f": isLowerCase("a c"),
"g": isLowerCase("a1c"),
"h": isLowerCase("a/c")
}
1
2
3
4
5
6
7
8
9
10
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": false,
"g": false,
"h": false
}
isLowerCase(text: Null): Boolean
Helper function that enables isLowerCase
to work with a null
value.
8.1.17. isNumeric
isNumeric(text: 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.
Parameters
Name | Description |
---|---|
text |
The input string. |
Example
This example shows how isNumeric
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
%dw 2.0
import isNumeric from dw::core::Strings
output application/json
---
{
"a": isNumeric(null),
"b": isNumeric(""),
"c": isNumeric(" "),
"d": isNumeric("123"),
"e": isNumeric("१२३"),
"f": isNumeric("12 3"),
"g": isNumeric("ab2c"),
"h": isNumeric("12-3"),
"i": isNumeric("12.3"),
"j": isNumeric("-123"),
"k": isNumeric("+123")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": true,
"f": false,
"g": false,
"h": false,
"i": false,
"j": false,
"k": false
}
isNumeric(text: Null): Boolean
Helper function that enables isNumeric
to work with a null
value.
8.1.18. isUpperCase
isUpperCase(text: String): Boolean
Checks if the text
contains only uppercase characters.
Parameters
Name | Description |
---|---|
text |
The input string. |
Example
This example shows how isUpperCase
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import isUpperCase from dw::core::Strings
output application/json
---
{
"a": isUpperCase(null),
"b": isUpperCase(""),
"c": isUpperCase(" "),
"d": isUpperCase("ABC"),
"e": isUpperCase("aBC"),
"f": isUpperCase("A C"),
"g": isUpperCase("A1C"),
"h": isUpperCase("A/C")
}
1
2
3
4
5
6
7
8
9
10
{
"a": false,
"b": false,
"c": false,
"d": true,
"e": false,
"f": false,
"g": false,
"h": false
}
isUpperCase(text: Null): Boolean
Helper function that enables isUpperCase
to work with a null
value.
8.1.19. isWhitespace
isWhitespace(text: String): Boolean
Checks if the text
contains only whitespace.
Parameters
Name | Description |
---|---|
text |
The input string. |
Example
This example shows how isWhitespace
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import isWhitespace from dw::core::Strings
output application/json
---
{
"a": isWhitespace(null),
"b": isWhitespace(""),
"c": isWhitespace(" "),
"d": isWhitespace("abc"),
"e": isWhitespace("ab2c"),
"f": isWhitespace("ab-c")
}
1
2
3
4
5
6
7
8
{
"a": false,
"b": true,
"c": true,
"d": false,
"e": false,
"f": false
}
isWhitespace(text: Null): Boolean
Helper function that enables isWhitespace
to work with a null
value.
8.1.20. last
last(text: String, amount: Number): String
Returns characters from the end of string to a specified number of characters, for example, the last two characters of a string.
Parameters
Name | Description |
---|---|
text |
The string to process. |
amount |
The number of characters to return. Negative
numbers and |
Example
This example returns the last six characters from a string.
1
2
3
4
5
%dw 2.0
import last from dw::core::Strings
output application/json
---
"hello world!" last 6
1
"world!"
last(text: Null, amount: Any): Null
Helper function that enables last
to work with a null
value.
8.1.21. leftPad
leftPad(text: String, size: Number, padText: 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.
Parameters
Name | Description |
---|---|
text |
The input string. |
size |
The size to pad to. |
padText |
The text to pad with. It defaults to one space if not specified. |
Example
This example shows how leftPad
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": leftPad(null, 3),
"b": leftPad("", 3),
"c": leftPad("bat", 5),
"d": leftPad("bat", 3),
"e": leftPad("bat", -1)
}
1
2
3
4
5
6
7
{
"a": null,
"b": " ",
"c": " bat",
"d": "bat",
"e": "bat"
}
leftPad(text: Null, size: Any, padText: Any = " "): Null
Helper function that enables leftPad
to work with a null
value.
8.1.22. levenshteinDistance
levenshteinDistance(a: String, b: String): Number
Returns the Levenshtein distance (or edit distance) between two strings.
Parameters
Name | Description |
---|---|
a |
The first string. |
b |
The second string. |
Example
This example shows how levenshteinDistance
behaves with different strings.
1
2
3
4
5
%dw 2.0
import levenshteinDistance from dw::core::Strings
output application/json
---
"kitten" levenshteinDistance "sitting"
1
3
8.1.23. lines
lines(text: String): Array<String>
Returns an array of lines from a string.
Parameters
Name | Description |
---|---|
text |
The string to split into lines. |
Example
This example divides a string into lines.
An \n
represents a line break.
1
2
3
4
5
%dw 2.0
import lines from dw::core::Strings
output application/json
---
lines("hello world\n\nhere data-weave")
1
["hello world", "", "here data-weave"]
lines(text: Null): Null
Helper function that enables lines
to work with a null
value.
8.1.24. mapString
mapString(@StreamCapable text: String, mapper: (character: String, index: Number) -> String): String
Applies an expression to every character of a string.
Parameters
Name | Description |
---|---|
text |
The string to map. |
mapper |
Expression that applies to each character ( |
Example
This example redacts sensitive data from a string.
1
2
3
4
5
%dw 2.0
import * from dw::core::Strings
output application/json
---
{ balance: ("\$234" mapString if (isNumeric($)) "~" else $) }
1
2
3
{
"balance": "$~~~"
}
mapString(@StreamCapable text: Null, mapper: (character: Nothing, index: Nothing) -> Any): Null
Helper function that enables mapString
to work with a null
value.
8.1.25. ordinalize
ordinalize(num: Number): String
Returns a number as an ordinal, such as 1st
or 2nd
.
Parameters
Name | Description |
---|---|
num |
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(num: Null): Null
Helper function that enables ordinalize
to work with a null
value.
8.1.26. pluralize
pluralize(text: String): String
Pluralizes a singular string.
If the input is already plural (for example, "boxes"), the output will match the input.
Parameters
Name | Description |
---|---|
text |
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(text: Null): Null
Helper function that enables pluralize
to work with a null
value.
8.1.27. prependIfMissing
prependIfMissing(text: String, prefix: String): String
Prepends the prefix
to the beginning of the string if the text
does not
already start with that prefix.
Parameters
Name | Description |
---|---|
text |
The input string. |
prefix |
The text to use as prefix. |
Example
This example shows how prependIfMissing
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import prependIfMissing from dw::core::Strings
output application/json
---
{
"a": prependIfMissing(null, ""),
"b": prependIfMissing("abc", ""),
"c": prependIfMissing("", "xyz"),
"d": prependIfMissing("abc", "xyz"),
"e": prependIfMissing("xyzabc", "xyz")
}
1
2
3
4
5
6
7
{
"a": null,
"b": "abc",
"c": "xyz",
"d": "xyzabc",
"e": "xyzabc"
}
prependIfMissing(text: Null, prefix: String): Null
Helper function that enables prependIfMissing
to work with a null
value.
8.1.28. remove
remove(text: String, toRemove: String): String
Removes all occurrences of a specified pattern from a string.
Parameters
Name | Description |
---|---|
text |
The text to remove from. |
toRemove |
The pattern to remove. |
Example
This example shows how the remove
can be used to remove some unwanted properties.
1
2
3
4
5
%dw 2.0
import remove from dw::core::Strings
output application/json
---
"lazyness purity state higher-order stateful" remove "state"
1
"lazyness purity higher-order ful"
remove(text: Null, toRemove: Any): Null
Helper function that enables remove
to work with a null
value.
8.1.29. repeat
repeat(text: String, times: Number): String
Repeats a text
the number of specified times
.
Parameters
Name | Description |
---|---|
text |
The input string. |
times |
Number of times to repeat char. Negative is treated as zero. |
Example
This example shows how repeat
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": repeat("e", 0),
"b": repeat("e", 3),
"c": repeat("e", -2)
}
1
2
3
4
5
{
"a": "",
"b": "eee",
"c": ""
}
repeat(text: Null, times: Any): Null
Helper function that enables repeat
to work with a null
value.
8.1.30. replaceAll
replaceAll(text: String, target: String, replacement: String): String
Replaces all substrings that match a literal search string with a specified replacement string.
Replacement proceeds from the beginning of the string to the end.
For example, the result of replacing "aa"
with "b"
in the
string` "aaa"
is "ba"
, rather than "ab"
.
Parameters
Name | Description |
---|---|
text |
The string to search. |
target |
The string to find and replace in |
replacement |
The replacement string. |
Example
This example shows how replaceAll
behaves with different inputs.
1
2
3
4
5
6
7
8
9
import * from dw::core::Strings
output application/json
---
{
a: replaceAll("Mariano", "a" , "A"),
b: replaceAll("AAAA", "AAA" , "B"),
c: replaceAll(null, "aria" , "A"),
d: replaceAll("Mariano", "j" , "Test"),
}
1
2
3
4
5
6
{
"a": "MAriAno",
"b": "BA",
"c": null,
"d": "Mariano"
}
replaceAll(text: Null, oldValue: String, newValue: String): Null
Helper function that enables replaceAll
to work with a null
value.
8.1.31. reverse
reverse(text: String): String
Reverses sequence of characters in a string.
Parameters
Name | Description |
---|---|
text |
The string to reverse. |
Example
This example shows how reverse
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
a: reverse("Mariano"),
b: reverse(null),
c: reverse("")
}
1
2
3
4
5
{
"a": "onairaM",
"b": null,
"c": ""
}
reverse(text: Null): Null
Helper function that enables reverse
to work with a null
value.
8.1.32. rightPad
rightPad(text: String, size: Number, padChar: 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.
Parameters
Name | Description |
---|---|
text |
The input string. |
size |
The size to pad to. |
padText |
The text to pad with. It defaults to one space if not specified. |
Example
This example shows how rightPad
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": rightPad(null, 3),
"b": rightPad("", 3),
"c": rightPad("bat", 5),
"d": rightPad("bat", 3),
"e": rightPad("bat", -1)
}
1
2
3
4
5
6
7
{
"a": null,
"b": " ",
"c": "bat ",
"d": "bat",
"e": "bat"
}
rightPad(text: Null, size: Any, padText: Any = " "): Null
Helper function that enables rightPad
to work with a null
value.
8.1.33. singularize
singularize(text: 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 |
---|---|
text |
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(text: Null): Null
Helper function that enables singularize
to work with a null
value.
8.1.34. someCharacter
someCharacter(text: String, condition: (character: String) -> Boolean): Boolean
Checks whether a condition is valid for at least one of the characters or blank spaces in a string.
Parameters
Name | Description |
---|---|
text |
The string to check. |
condition |
Expression that iterates through the characters and spaces in the string and returns a Boolean value. |
Example
This example determines whether a string has any uppercase characters.
1
2
3
4
5
%dw 2.0
import * from dw::core::Strings
output application/json
---
"someCharacter" someCharacter isUpperCase($)
1
true
someCharacter(text: Null, condition: (character: Nothing) -> Any): false
Helper function that enables someCharacter
to work with a null
value.
8.1.35. substring
substring(text: String, from: Number, until: Number): String
Returns a substring that spans from the character at the
specified from
index to the last character before the
until
index.
The characters in the substring satisfy the condition
from <= indexOf(string) < until
.
Parameters
Name | Description |
---|---|
text |
The string, treated as an array of characters. |
from |
The lowest index to include from the character array. |
until |
The lowest index to exclude from the character array. |
Example
This example returns the substring with characters at indices
1
through 4
in the input string.
1
2
3
4
5
6
%dw 2.0
import * from dw::core::Strings
output application/json
var text = "hello world!"
---
substring(text, 1, 5)
1
"ello"
substring(text: Null, from: Any, until: Any): Null
Helper function that enables substring
to work with a null
value.
8.1.36. substringAfter
substringAfter(text: String, separator: String): String
Gets the substring after the first occurrence of a separator. The separator is not returned.
Parameters
Name | Description |
---|---|
text |
The input string. |
separator |
String to search for. |
Example
This example shows how substringAfter
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": substringAfter(null, "'"),
"b": substringAfter("", "-"),
"c": substringAfter("abc", "b"),
"d": substringAfter("abcba", "b"),
"e": substringAfter("abc", "d"),
"f": substringAfter("abc", "")
}
1
2
3
4
5
6
7
8
9
{
"a": null,
"b": "",
"c": "c",
"d": "cba",
"e": "",
"f": "bc"
}
substringAfter(text: Null, separator: String): Null
Helper function that enables substringAfter
to work with a null
value.
8.1.37. substringAfterLast
substringAfterLast(text: String, separator: String): String
Gets the substring after the last occurrence of a separator. The separator is not returned.
Parameters
Name | Description |
---|---|
text |
The input string. |
separator |
String to search for. |
Example
This example shows how substringAfterLast
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": substringAfterLast(null, "'"),
"b": substringAfterLast("", "-"),
"c": substringAfterLast("abc", "b"),
"d": substringAfterLast("abcba", "b"),
"e": substringAfterLast("abc", "d"),
"f": substringAfterLast("abc", "")
}
1
2
3
4
5
6
7
8
{
"a": null,
"b": "",
"c": "c",
"d": "a",
"e": "",
"f": null
}
substringAfterLast(text: Null, separator: String): Null
Helper function that enables substringAfterLast
to work with a null
value.
8.1.38. substringBefore
substringBefore(text: String, separator: String): String
Gets the substring before the first occurrence of a separator. The separator is not returned.
Parameters
Name | Description |
---|---|
text |
The input string. |
separator |
String to search for. |
Example
This example shows how substringBefore
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": substringBefore(null, "'"),
"b": substringBefore("", "-"),
"c": substringBefore("abc", "b"),
"d": substringBefore("abc", "c"),
"e": substringBefore("abc", "d"),
"f": substringBefore("abc", "")
}
1
2
3
4
5
6
7
8
{
"a": null,
"b": "",
"c": "a",
"d": "ab",
"e": "",
"f": ""
}
substringBefore(text: Null, separator: String): Null
Helper function that enables substringBefore
to work with a null
value.
8.1.39. substringBeforeLast
substringBeforeLast(text: String, separator: String): String
Gets the substring before the last occurrence of a separator. The separator is not returned.
Parameters
Name | Description |
---|---|
text |
The input string. |
separator |
String to search for. |
Example
This example shows how substringBeforeLast
behaves with different inputs
and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": substringBeforeLast(null, "'"),
"b": substringBeforeLast("", "-"),
"c": substringBeforeLast("abc", "b"),
"d": substringBeforeLast("abcba", "b"),
"e": substringBeforeLast("abc", "d"),
"f": substringBeforeLast("abc", "")
}
1
2
3
4
5
6
7
8
{
"a": null,
"b": "",
"c": "a",
"d": "abc",
"e": "",
"f": "ab"
}
substringBeforeLast(text: Null, separator: String): Null
Helper function that enables substringBeforeLast
to work with a null
value.
8.1.40. substringBy
substringBy(text: String, predicate: (character: String, index: Number) -> Boolean): Array<String>
Splits a string at each character where the predicate
expression
returns true
.
Parameters
Name | Description |
---|---|
text |
The string to split. The string is treated as an array of characters. |
predicate |
Expression that tests each character and returns a Boolean value. The expression can iterate over each character and index of the string. |
Example
This example splits a string where any of the specified characters
("~"
, "="
, or "_"
) are present.
1
2
3
4
5
%dw 2.0
import substringBy from dw::core::Strings
output application/json
---
"hello~world=here_data-weave" substringBy $ == "~" or $ == "=" or $ == "_"
1
["hello", "world", "here", "data-weave"]
substringBy(text: Null, predicate: (character: Nothing, index: Nothing) -> Any): Null
Helper function that enables substringBy
to work with a null
value.
8.1.41. substringEvery
substringEvery(text: String, amount: Number): Array<String>
Splits a string into an array of substrings equal to a specified length.
The last substring can be shorter than that length. If the length is greater than or equal to the length of the string to split, the function returns the entire string.
Parameters
Name | Description |
---|---|
text |
The string to split. |
amount |
The desired length of each substring. |
Example
This example shows how substringEvery
behaves when splitting an
input string. The last returned substring is shorter than the others.
1
2
3
4
5
%dw 2.0
import substringEvery from dw::core::Strings
output application/json
---
substringEvery("substringEvery", 3)
1
["sub", "str", "ing", "Eve", "ry"]
substringEvery(text: Null, amount: Any): Null
Helper function that enables substringEvery
to work with a null
value.
8.1.42. underscore
underscore(text: 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 |
---|---|
text |
The input string. |
Example
This example replaces the hyphens and spaces in the input. Notice that the input "customer" is not modified in the output.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a" : underscore("customer"),
"b" : underscore("customer-first-name"),
"c" : underscore("customer NAME"),
"d" : underscore("customerName")
}
1
2
3
4
5
6
{
"a": "customer",
"b": "customer_first_name",
"c": "customer_name",
"d": "customer_name"
}
underscore(text: Null): Null
Helper function that enables underscore
to work with a null
value.
8.1.43. unwrap
unwrap(text: String, wrapper: String): String
Unwraps a given text
from a wrapper
text.
Parameters
Name | Description |
---|---|
text |
The input string. |
wrapper |
The text used to unwrap. |
Example
This example shows how unwrap
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
import unwrap from dw::core::Strings
output application/json
---
{
"a": unwrap(null, ""),
"b": unwrap(null, '\0'),
"c": unwrap("'abc'", "'"),
"d": unwrap("AABabcBAA", 'A'),
"e": unwrap("A", '#'),
"f": unwrap("#A", '#'),
"g": unwrap("A#", '#')
}
1
2
3
4
5
6
7
8
9
{
"a": null,
"b": null,
"c": "abc",
"d": "ABabcBA",
"e": "A",
"f": "#A",
"g": "A#"
}
unwrap(text: Null, wrapper: String): Null
Helper function that enables unwrap
to work with a null
value.
8.1.44. withMaxSize
withMaxSize(text: String, maxLength: Number): String
Checks that the string length is no larger than the specified maxLength
.
If the string’s length is larger than the maxLength
, the function cuts
characters from left to right, until the string length meets the length limit.
Parameters
Name | Description |
---|---|
text |
The input string. |
maxLength |
The maximum length of the string. |
Example
This example shows how withMaxSize
behaves with different maxLength
values for the same string.
Note that if withMaxSize
is 0, the function returns an unmodified string. If
the input is null
, the output is always null
.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import withMaxSize from dw::core::Strings
output application/json
---
{
a: "123" withMaxSize 10,
b: "123" withMaxSize 3,
c: "123" withMaxSize 2,
d: "123" withMaxSize 0,
e: null withMaxSize 23,
}
1
2
3
4
5
6
7
{
"a": "123",
"b": "123",
"c": "12",
"d": "123",
"e": null
}
withMaxSize(text: Null, maxLength: Number): Null
Helper function that enables withMaxSize
to work with a null
value.
8.1.45. words
words(text: String): Array<String>
Returns an array of words from a string.
Separators between words include blank spaces, new lines, and tabs.
Parameters
Name | Description |
---|---|
text |
The string to split into words. |
Example
This example divides a string by the words
it contains.
An \n
represents a line break, and \t
represents a tab.
1
2
3
4
5
%dw 2.0
import words from dw::core::Strings
output application/json
---
words("hello world\nhere\t\t\tdata-weave")
1
["hello", "world", "here", "data-weave"]
words(text: Null): Null
Helper function that enables words
to work with a null
value.
8.1.46. wrapIfMissing
wrapIfMissing(text: String, wrapper: String): String
Wraps text
with wrapper
if that wrapper
is missing from the start or
end of the given string.
Parameters
Name | Description |
---|---|
text |
The input string. |
wrapper |
The content used to wrap. |
Example
This example shows how wrapIfMissing
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": wrapIfMissing(null, "'"),
"b": wrapIfMissing("", "'"),
"c": wrapIfMissing("ab", "x"),
"d": wrapIfMissing("'ab'", "'"),
"e": wrapIfMissing("/", '/'),
"f": wrapIfMissing("a/b/c", '/'),
"g": wrapIfMissing("/a/b/c", '/'),
"h": wrapIfMissing("a/b/c/", '/')
}
1
2
3
4
5
6
7
8
9
10
{
"a": null,
"b": "'",
"c": "xabx",
"d": "'ab'",
"e": "/",
"f": "/a/b/c/",
"g": "/a/b/c/",
"h": "/a/b/c/"
}
wrapIfMissing(text: Null, wrapper: String): Null
Helper function that enables wrapIfMissing
to work with a null
value.
8.1.47. wrapWith
wrapWith(text: String, wrapper: String): String
Wraps the specified text
with the given wrapper
.
Parameters
Name | Description |
---|---|
text |
The input string. |
wrapper |
The content used to wrap. |
Example
This example shows how wrapWith
behaves with different inputs and sizes.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::Strings
output application/json
---
{
"a": wrapWith(null, "'"),
"b": wrapWith("", "'"),
"c": wrapWith("ab", "x"),
"d": wrapWith("'ab'", "'"),
"e": wrapWith("ab", "'")
}
1
2
3
4
5
6
7
{
"a": null,
"b": "''",
"c": "xabx",
"d": "''ab''",
"e": "'ab'"
}
wrapWith(text: Null, wrapper: Any): Null
Helper function that enables wrapWith
to work with a null
value.
9. dw::core::Types
This module enables you to perform type introspection.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::core::Types
to the header of your
DataWeave script.
9.1. Functions
9.1.1. arrayItem
arrayItem(t: Type): Type
Returns the type of the given array. This function fails if the input is not an Array type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how arrayItem
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import * from dw::core::Types
type ArrayOfString = Array<String>
type ArrayOfNumber = Array<Number>
type ArrayOfAny = Array<Any>
type ArrayOfAnyDefault = Array
output application/json
---
{
a: arrayItem(ArrayOfString),
b: arrayItem(ArrayOfNumber),
c: arrayItem(ArrayOfAny),
d: arrayItem(ArrayOfAnyDefault)
}
1
2
3
4
5
6
{
"a": "String",
"b": "Number",
"c": "Any",
"d": "Any"
}
9.1.2. baseTypeOf
baseTypeOf(t: Type): Type
Returns an the base type of the given type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how baseTypeOf
behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::core::Types
type AType = String {format: "YYYY-MM-dd"}
output application/json
---
{
a: baseTypeOf(AType)
}
1
2
3
{
"a": "String"
}
9.1.3. functionParamTypes
functionParamTypes(t: Type): Array<FunctionParam>
Returns the list of parameters from the given function type. This function fails if the provided type is not a Function type.
Parameters
Name | Description |
---|---|
t |
The function type. |
Example
This example shows how functionParamTypes
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
import * from dw::core::Types
type AFunction = (String, Number) -> Number
type AFunction2 = () -> Number
---
{
a: functionParamTypes(AFunction),
b: functionParamTypes(AFunction2)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"a": [
{
"paramType": "String",
"optional": false
},
{
"paramType": "Number",
"optional": false
}
],
"b": [
]
}
9.1.4. functionReturnType
functionReturnType(t: Type): Type | Null
Returns the type of a function’s return type. This function fails if the input type is not a Function type.
Parameters
Name | Description |
---|---|
t |
The function type. |
Example
This example shows how functionReturnType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
output application/json
import * from dw::core::Types
type AFunction = (String, Number) -> Number
type AFunction2 = () -> Number
---
{
a: functionReturnType(AFunction),
b: functionReturnType(AFunction2)
}
1
2
3
4
{
"a": "Number",
"b": "Number"
}
9.1.5. intersectionItems
intersectionItems(t: Type): Array<Type>
Returns an array of all the types that define a given Intersection type. This function fails if the input is not an Intersection type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how intersectionItems
behaves with different inputs.
Note that the AType
variable defines an Intersection type
{name: String} & {age: Number}
by using an &
between
the two objects.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::core::Types
type AType = {name: String} & {age: Number}
output application/json
---
{
a: intersectionItems(AType)
}
1
2
3
{
"a": ["Object","Object"]
}
9.1.6. isAnyType
isAnyType(t: Type): Boolean
Returns true
if the input is the Any type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isAnyType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type AAny = Any
output application/json
---
{
a: isAnyType(AAny),
b: isAnyType(Any),
c: isAnyType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.7. isArrayType
isArrayType(t: Type): Boolean
Returns true
if the input type is the Array type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isArrayType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AType = Array<String>
output application/json
---
{
a: isArrayType(AType),
b: isArrayType(Boolean),
}
1
2
3
4
{
"a": true,
"b": false
}
9.1.8. isBinaryType
isBinaryType(t: Type): Boolean
Returns true
if the input is the Binary type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isBinaryType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ABinary = Binary
output application/json
---
{
a: isBinaryType(ABinary),
b: isBinaryType(Binary),
c: isBinaryType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.9. isBooleanType
isBooleanType(t: Type): Boolean
Returns true
if the input is the Boolean type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isBooleanType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ABoolean = Boolean
output application/json
---
{
a: isBooleanType(ABoolean),
b: isBooleanType(Boolean),
c: isBooleanType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.10. isDateTimeType
isDateTimeType(t: Type): Boolean
Returns true
if the input is the DateTime type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isDateTimeType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ADateTime = DateTime
output application/json
---
{
a: isDateTimeType(ADateTime),
b: isDateTimeType(DateTime),
c: isDateTimeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.11. isDateType
isDateType(t: Type): Boolean
Returns true
if the input is the Date type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isDateType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ADate = Date
output application/json
---
{
a: isDateType(ADate),
b: isDateType(Date),
c: isDateType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.12. isFunctionType
isFunctionType(t: Type): Boolean
Returns true
if the input is the Function type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isFunctionType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AFunction = (String) -> String
output application/json
---
{
a: isFunctionType(AFunction),
b: isFunctionType(Boolean)
}
1
2
3
4
{
"a": true,
"b": false
}
9.1.13. isIntersectionType
isIntersectionType(t: Type): Boolean
Returns true
if the input type is the Intersection type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isIntersectionType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AType = {name: String} & {age: Number}
output application/json
---
{
a: isIntersectionType(AType),
b: isIntersectionType(Boolean),
}
1
2
3
4
{
"a": true,
"b": false
}
9.1.14. isKeyType
isKeyType(t: Type): Boolean
Returns true
if the input is the Key type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isKeyType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type AKey = Key
output application/json
---
{
a: isKeyType(AKey),
b: isKeyType(Key),
c: isKeyType(Boolean),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.15. isLiteralType
isLiteralType(t: Type): Boolean
Returns true
if the input is the Literal type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isLiteralType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type ALiteralType = "Mariano"
output application/json
---
{
a: isLiteralType(ALiteralType),
b: isLiteralType(Boolean)
}
1
2
3
4
{
"a": true,
"b": false
}
9.1.16. isLocalDateTimeType
isLocalDateTimeType(t: Type): Boolean
Returns true
if the input is the LocalDateTime type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isLocalDateTimeType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ALocalDateTime = LocalDateTime
output application/json
---
{
a: isLocalDateTimeType(ALocalDateTime),
b: isLocalDateTimeType(LocalDateTime),
c: isLocalDateTimeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.17. isLocalTimeType
isLocalTimeType(t: Type): Boolean
Returns true
if the input is the LocalTime type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isLocalTimeType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ALocalTime = LocalTime
output application/json
---
{
a: isLocalTimeType(ALocalTime),
b: isLocalTimeType(LocalTime),
c: isLocalTimeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.18. isNamespaceType
isNamespaceType(t: Type): Boolean
Returns true
if the input is the Namespace type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isNamespaceType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ANamespace = Namespace
output application/json
---
{
a: isNamespaceType(ANamespace),
b: isNamespaceType(Namespace),
c: isNamespaceType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.19. isNothingType
isNothingType(t: Type): Boolean
Returns true
if the input is the Nothing type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isNothingType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ANothing = Nothing
output application/json
---
{
a: isNothingType(ANothing),
b: isNothingType(Nothing),
c: isNothingType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.20. isNullType
isNullType(t: Type): Boolean
Returns true
if the input is the Null type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isNullType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ANull = Null
output application/json
---
{
a: isNullType(ANull),
b: isNullType(Null),
c: isNullType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.21. isNumberType
isNumberType(t: Type): Boolean
Returns true
if the input is the Number type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isNumberType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ANumber = Number
output application/json
---
{
a: isNumberType(ANumber),
b: isNumberType(Number),
c: isNumberType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.22. isObjectType
isObjectType(t: Type): Boolean
Returns true
if the input is the Object type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isObjectType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AType = {name: String}
output application/json
---
{
a: isObjectType(AType),
b: isObjectType(Boolean),
}
1
2
3
4
{
"a": true,
"b": false
}
9.1.23. isPeriodType
isPeriodType(t: Type): Boolean
Returns true
if the input is the Period type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isPeriodType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type APeriod = Period
output application/json
---
{
a: isPeriodType(APeriod),
b: isPeriodType(Period),
c: isPeriodType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.24. isRangeType
isRangeType(t: Type): Boolean
Returns true
if the input is the Range type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isRangeType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ARange = Range
output application/json
---
{
a: isRangeType(ARange),
b: isRangeType(Range),
c: isRangeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.25. isReferenceType
isReferenceType(t: Type): Boolean
Returns true
if the input type is a Reference type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isReferenceType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
output application/json
import * from dw::core::Types
type AArray = Array<String> {n: 1}
type AArray2 = Array<AArray>
---
{
a: isReferenceType( AArray),
b: isReferenceType(arrayItem(AArray2)),
c: isReferenceType(String)
}
1
2
3
4
5
{
"a": false,
"b": true,
"c": false
}
9.1.26. isRegexType
isRegexType(t: Type): Boolean
Returns true
if the input is the Regex type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isRegexType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ARegex = Regex
output application/json
---
{
a: isRegexType(ARegex),
b: isRegexType(Regex),
c: isRegexType(Boolean),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.27. isStringType
isStringType(t: Type): Boolean
Returns true
if the input is the String type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isStringType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type AString = String
output application/json
---
{
a: isStringType(AString),
b: isStringType(String),
c: isStringType(Boolean),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.28. isTimeType
isTimeType(t: Type): Boolean
Returns true
if the input is the Time type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isTimeType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ATime = Time
output application/json
---
{
a: isTimeType(ATime),
b: isTimeType(Time),
c: isTimeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.29. isTimeZoneType
isTimeZoneType(t: Type): Boolean
Returns true
if the input is the TimeZone type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isTimeZoneType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type ATimeZone = TimeZone
output application/json
---
{
a: isTimeZoneType(ATimeZone),
b: isTimeZoneType(TimeZone),
c: isTimeZoneType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.30. isTypeType
isTypeType(t: Type): Boolean
Returns true
if the input is the Type type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isTypeType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type AType = Type
output application/json
---
{
a: isTypeType(AType),
b: isTypeType(Type),
c: isTypeType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.31. isUnionType
isUnionType(t: Type): Boolean
Returns true
if the input type is the Union type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isUnionType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::core::Types
type AType = String | Number
output application/json
---
{
a: isUnionType(AType),
b: isUnionType(Boolean),
}
1
2
3
4
{
"a": true,
"b": false
}
9.1.32. isUriType
isUriType(t: Type): Boolean
Returns true
if the input is the Uri type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how isUriType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::core::Types
type AUri = Uri
output application/json
---
{
a: isUriType(AUri),
b: isUriType(Uri),
c: isUriType(String),
}
1
2
3
4
5
{
"a": true,
"b": true,
"c": false
}
9.1.33. literalValueOf
literalValueOf(t: Type): String | Number | Boolean
Returns the value of an input belongs to the Literal type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how literalValueOf
behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::core::Types
type AType = "Mariano"
output application/json
---
{
a: literalValueOf(AType)
}
1
2
3
{
"a": "Mariano"
}
9.1.34. metadataOf
metadataOf(t: Type): Object
Returns metadata that is attached to the given type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how metadataOf
behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::core::Types
type AType = String {format: "YYYY-MM-dd"}
output application/json
---
{
a: metadataOf(AType)
}
1
2
3
{
"a": {"format": "YYYY-MM-dd"}
}
9.1.35. nameOf
nameOf(t: Type): String
Returns the name of the input type.
Parameters
Name | Description |
---|---|
t |
The type to query |
Example
This example shows how nameOf
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
output application/json
import * from dw::core::Types
type AArray = Array<String> {n: 1}
type AArray2 = Array<String>
---
{
a: nameOf(AArray),
b: nameOf(AArray2),
c: nameOf(String)
}
1
2
3
4
5
{
"a": "AArray",
"b": "AArray2",
"c": "String"
}
9.1.36. objectFields
objectFields(t: Type): Array<Field>
Returns the array of fields from the given Object type. This function fails if the type is not an Object type.
Parameters
Name | Description |
---|---|
t |
The function type. |
Example
This example shows how objectFields
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
import * from dw::core::Types
ns ns0 http://acme.com
type ADictionary = {_ : String}
type ASchema = {ns0#name @(ns0#foo: String): {}}
type AUser = {name @(foo?: String,l: Number)?: String, lastName*: Number}
---
{
a: objectFields(ADictionary),
b: objectFields(ASchema),
c: objectFields(Object),
d: objectFields(AUser)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
{
"a": [
{
"key": {
"name": {
"localName": "_",
"namespace": null
},
"attributes": [
]
},
"required": true,
"repeated": false,
"value": "String"
}
],
"b": [
{
"key": {
"name": {
"localName": "name",
"namespace": "http://acme.com"
},
"attributes": [
{
"name": {
"localName": "foo",
"namespace": "http://acme.com"
},
"value": "String",
"required": true
}
]
},
"required": true,
"repeated": false,
"value": "Object"
}
],
"c": [
],
"d": [
{
"key": {
"name": {
"localName": "name",
"namespace": null
},
"attributes": [
{
"name": {
"localName": "foo",
"namespace": null
},
"value": "String",
"required": false
},
{
"name": {
"localName": "l",
"namespace": null
},
"value": "Number",
"required": true
}
]
},
"required": false,
"repeated": false,
"value": "String"
},
{
"key": {
"name": {
"localName": "lastName",
"namespace": null
},
"attributes": [
]
},
"required": true,
"repeated": true,
"value": "Number"
}
]
}
9.1.37. unionItems
unionItems(t: Type): Array<Type>
Returns an array of all the types that define a given Union type. This function fails if the input is not a Union type.
Parameters
Name | Description |
---|---|
t |
The type to check. |
Example
This example shows how unionItems
behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::core::Types
type AType = String | Number
output application/json
---
{
a: unionItems(AType)
}
1
2
3
{
"a": ["String","Number"]
}
9.2. Types
9.2.1. Attribute
Represents an Attribute definition that is part of an Object field Key.
1
{ name: QName, required: Boolean, value: Type }
9.2.2. Field
Represents a Field description that is part of an Object.
1
{ key: { name: QName, attributes: Array<Attribute> }, required: Boolean, repeated: Boolean, value: Type }
9.2.3. FunctionParam
Represents a Function parameter that is part of a Function type.
1
{ paramType: Type, optional: Boolean }
9.2.4. QName
Represents a Qualified Name definition with a localName
(a string) and a namespace
.
If the QName does not have a Namespace, its value is null
.
1
{ localName: String, namespace: Namespace | Null }
10. dw::core::URL
This module contains helper functions for working with URIs.
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(parts: Array<String>, interpolation: Array<String>): String
Uses a custom string interpolator to replace URL components with a
encodeURIComponent
result. You can call this function using the standard call, or a simplified version.
Parameters
Name | Description |
---|---|
baseStringArray |
A string array that contains the URL parts to interpolate using the strings in the |
interpolationStringArray |
A string array that contains the strings used to interpolate the |
Example
The following example uses the compose function to form an encoded URL, the first parameter is an array of two strings that are part of the URL
and the second parameter is the urlPath
variable that is used to interpolate the strings in the first parameter.
Notice that the spaces in the input are encoded in the output URL as %20
.
1
2
3
4
5
6
%dw 2.0
output application/json
var urlPath = "content folder"
import * from dw::core::URL
---
{ "encodedURL" : compose(["http://examplewebsite.com/", "/page.html"], ["$(urlPath)"]) }
1
{ "encodedURL" : "http://examplewebsite.com/content%20folder/page.html" }
Example
You can also call this function using the simplified syntax, which uses backticks (`
) to enclose the string that includes the variable
to encode. This example shows how to use the simplified syntax to obtain the same result as in the previous example.
1
2
3
4
5
6
%dw 2.0
output application/json
var urlPath = "content folder"
import * from dw::core::URL
---
{ "encodedURL" : compose `http://examplewebsite.com/$(urlPath)/page.html`}
1
{ "encodedURL" : "http://examplewebsite.com/content%20folder/page.html" }
10.1.2. decodeURI
decodeURI(text: 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 |
---|---|
text |
The URI to decode. |
Example
This example decodes a URI that contains the URL percent encoding %20
,
which is used for spaces.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::URL
output application/json
---
{
"decodeURI" : decodeURI('http://asd/%20text%20to%20decode%20/text')
}
1
2
3
{
"decodeURI": "http://asd/ text to decode /text"
}
10.1.3. decodeURIComponent
decodeURIComponent(text: String): String
Decodes a Uniform Resource Identifier (URI) component previously created
by encodeURIComponent
or a similar routine.
For an example, see encodeURIComponent
.
Parameters
Name | Description |
---|---|
text |
URI component string. |
Example
This example decodes a variety of URI components.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::core::URL
output application/json
---
{
"decodeURIComponent": {
"decodeURIComponent" : decodeURIComponent("%20PATH/%20TO%20/DECODE%20"),
"decodeURIComponent" : decodeURIComponent("%3B%2C%2F%3F%3A%40%26%3D"),
"decodeURIComponent" : decodeURIComponent("%2D%5F%2E%21%7E%2A%27%28%29%24"),
}
}
1
2
3
4
5
6
7
{
decodeURIComponent: {
decodeURIComponent: " PATH/ TO /DECODE ",
decodeURIComponent: ";,/?:@&=",
decodeURIComponent: "-_.!~*'()\$"
}
}
10.1.4. encodeURI
encodeURI(text: String): String
Encodes a URI with UTF-8 escape sequences.
Applies up to four escape sequences for characters composed of two "surrogate" characters. The function assumes that the URI is a complete URI, so it does not encode reserved characters that have special meaning.
The function does not encode these characters with UTF-8 escape sequences:
Type (not escaped) | Examples |
---|---|
Reserved characters |
; , / ? : @ & = $ |
Unescaped characters |
alphabetic, decimal digits, - _ . ! ~ * ' ( ) |
Number sign |
# |
Parameters
Name | Description |
---|---|
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.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::core::URL
output application/json
---
{
"encodeURI" : encodeURI("http://asd/ text to decode /text"),
"not_encoded": encodeURI("http://:;,/?:@&=\$_-_.!~*'()")
}
1
2
3
4
{
"encodeURI": "http://asd/%20text%20to%20decode%20/%25/\"\'/text",
"not_encoded": "http://:;,/?:@&=$_-_.!~*'()"
}
10.1.5. encodeURIComponent
encodeURIComponent(text: String): String
Escapes certain characters in a URI component using UTF-8 encoding.
There can be only four escape sequences for characters composed of two
"surrogate" * characters. encodeURIComponent
escapes all characters
except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
.
Note that encodeURIComponent
differs from encodeURI
in that it encodes
reserved characters and the Number sign #
of encodeURI
:
Type | Includes |
---|---|
Reserved characters |
|
Unescaped characters |
alphabetic, decimal digits, - _ . ! ~ * ' ( ) |
Number sign |
Parameters
Name | Description |
---|---|
text |
URI component string. |
Example
This example encodes a variety of URI components.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import * from dw::core::URL
output application/json
---
{
"comparing_encode_functions_output" : {
"encodeURIComponent" : encodeURI(" PATH/ TO /ENCODE "),
"encodeURI" : encodeURI(" PATH/ TO /ENCODE "),
"encodeURIComponent_to_hex" : encodeURIComponent(";,/?:@&="),
"encodeURI_not_to_hex" : encodeURI(";,/?:@&="),
"encodeURIComponent_not_encoded" : encodeURIComponent("-_.!~*'()"),
"encodeURI_not_encoded" : encodeURI("-_.!~*'()")
}
}
1
2
3
4
5
6
7
8
9
10
{
"comparing_encode_functions_output": {
"encodeURIComponent": "%20PATH/%20TO%20/ENCODE%20",
"encodeURI": "%20PATH/%20TO%20/ENCODE%20",
"encodeURIComponent_to_hex": "%3B%2C%2F%3F%3A%40%26%3D",
"encodeURI_not_to_hex": ";,/?:@&=",
"encodeURIComponent_not_encoded": "-_.!~*'()",
"encodeURI_not_encoded": "-_.!~*'()"
}
}
10.1.6. parseURI
parseURI(uri: String): URI
Parses a URL and returns a URI
object.
The isValid: Boolean
property in the output URI
object indicates whether
the parsing process succeeded. Every field in this object is optional, and
a field will appear in the output only if it was present in the URL input.
Parameters
Name | Description |
---|---|
uri |
The URI input. |
Example
This example parses a URL.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::core::URL
output application/json
---
{
'composition': parseURI('https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#footer')
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"composition": {
"isValid": true,
"raw": "https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#footer",
"host": "en.wikipedia.org",
"authority": "en.wikipedia.org",
"fragment": "footer",
"path": "/wiki/Uniform_Resource_Identifier",
"scheme": "https",
"isAbsolute": true,
"isOpaque": false
}
}
10.2. Types
10.2.1. URI
Describes the URI type. For descriptions of the fields, see URL Types (dw::core::URL).
1
{ isValid: Boolean, host?: String, authority?: String, fragment?: String, path?: String, port?: Number, query?: String, scheme?: String, user?: String, isAbsolute?: Boolean, isOpaque?: Boolean }
11. 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.
11.1. Functions
11.1.1. HMACBinary
HMACBinary(secret: Binary, content: Binary, algorithm: String = "HmacSHA1"): Binary
Computes an HMAC hash (with a secret cryptographic key) on input content.
See also, HMACWith
.
Parameters
Name | Description |
---|---|
secret |
The secret cryptographic key (a binary value) used when encrypting the |
content |
The binary input value. |
algorithm |
The hashing algorithm. |
Example
This example uses HMAC with a secret value to encrypt the input content.
1
2
3
4
5
6
7
%dw 2.0
import dw::Crypto
output application/json
---
{
"HMACBinary" : Crypto::HMACBinary("confidential" as Binary, "xxxxx" as Binary, "HmacSHA512")
}
1
2
3
{
"HMACBinary": "\ufffd\ufffd\ufffd\ufffd^h\ufffd!3\u0005\ufffdÖŽ\u00017\ufffd\ufffd\ufffd`\ufffd8?\ufffdjn7\ufffdbs;\t\ufffdÆ…\ufffd\ufffd\ufffdx&g\ufffd~\ufffd\ufffd%\ufffd7>1\ufffdK\u000e@\ufffdC\u0011\ufffdT\ufffd}W"
}
11.1.2. HMACWith
HMACWith(secret: Binary, content: Binary, @Since(version = "2.2.0") algorithm: String = "HmacSHA1"): 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 |
---|---|
secret |
The secret cryptographic key (a binary value) used when encrypting the |
content |
The binary input value. |
algorithm |
(Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.) The hashing algorithm. By default, |
Example
This example uses HMAC with a secret value to encrypt the input content using the HmacSHA256
algorithm.
1
2
3
4
5
%dw 2.0
import dw::Crypto
output application/json
---
{ "HMACWith" : Crypto::HMACWith("secret_key" as Binary, "Some value to hash" as Binary, "HmacSHA256") }
1
{ "HMACWith": "b51b4fe8c4e37304605753272b5b4321f9644a9b09cb1179d7016c25041d1747" }
11.1.3. MD5
MD5(content: Binary): String
Computes the MD5 hash and transforms the binary result into a hexadecimal lower case string.
Parameters
Name | Description |
---|---|
content |
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" }
11.1.4. SHA1
SHA1(content: Binary): String
Computes the SHA1 hash and transforms the result into a hexadecimal, lowercase string.
Parameters
Name | Description |
---|---|
content |
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" }
11.1.5. hashWith
hashWith(content: Binary, algorithm: String = "SHA-1"): Binary
Computes the hash value of binary content using a specified algorithm.
The first argument specifies the binary content to use to calculate the hash value, and the second argument specifies the hashing algorithm to use. The second argument must be any of the accepted Algorithm names:
Algorithm names | Description |
---|---|
|
The MD2 message digest algorithm as defined in RFC 1319. |
|
The MD5 message digest algorithm as defined in RFC 1321. |
|
Hash algorithms defined in the FIPS PUB 180-2. SHA-256 is a 256-bit hash function intended to provide 128 bits of security against collision attacks, while SHA-512 is a 512-bit hash function intended to provide 256 bits of security. A 384-bit hash may be obtained by truncating the SHA-512 output. |
Parameters
Name | Description |
---|---|
content |
The binary input value to hash. |
algorithm |
The name of the algorithm to use for calculating the hash value of |
Example
This example uses the MD2 algorithm to encrypt a binary value.
1
2
3
4
5
%dw 2.0
import dw::Crypto
output application/json
---
{ "md2" : Crypto::hashWith("hello" as Binary, "MD2") }
1
{ "md2": "\ufffd\u0004ls\ufffd\u00031\ufffdh\ufffd}8\u0004\ufffd\u0006U" }
12. dw::extension::DataFormat
This module provides resources for registering a new data format for the DataWeave language.
For an example, see Custom Data Formats Example.
12.1. Types
12.1.1. DataFormat
Represents the DataFormat
definition and contains the following fields:
-
binaryFormat
: True if this is data format is represented as binary representation instead of text. False if not present. -
defaultCharset
: Default character set of this format, if any. -
fileExtensions
: Returns the list of file extensions with the.
(for example,.json
,.xml
) to assign to this data format. -
acceptedMimeTypes
: The list of MIME types to accept. -
reader
: Function that reads raw content and transforms it into the canonical DataWeave model. -
writer
: Function that writes the canonical DataWeave model into binary content.
1
{ binaryFormat?: Boolean, defaultCharset?: String, fileExtensions?: Array<String>, acceptedMimeTypes: Array<MimeType>, reader: (content: Binary, charset: String, settings: ReaderSettings) -> Any, writer: (value: Any, settings: WriterSettings) -> Binary }
12.1.2. EmptySettings
Represents a configuration with no settings.
1
Object
12.1.3. EncodingSettings
Represents encoding settings and contains the following field:
-
encoding
: Encoding that the writer uses for output. Defaults to "UTF-8".
1
{ encoding?: String {defaultValue: "UTF-8"} }
12.1.4. MimeType
Represents a MIME type, such as application/json
.
1
String
12.1.5. Settings
Reader or writer configuration settings.
1
Object
12.2. Annotations
12.2.1. @DataFormatExtension()
Registration hook that the DataWeave engine uses to discover the variable that represents the custom data format. For an example, see the Custom Data Formats Example README.
13. 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.
13.1. Functions
13.1.1. field
field(opts: {| name: String, value: Any, mime?: String, fileName?: String |}): MultipartPart
Creates a MultipartPart
data structure using the specified part name,
input content for the part, format (or mime type), and optionally, file name.
This version of the field
function accepts arguments as an array of objects
that use the parameter names as keys, for example:
Multipart::field({name:"order",value: myOrder, mime: "application/json", fileName: "order.json"})
Parameters
Name | Description |
---|---|
opts |
Array of objects that specifies:
|
Example
This example creates a Multipart
data structure that contains parts.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import dw::module::Multipart
output multipart/form-data
var firstPart = "content for my first part"
var secondPart = "content for my second part"
---
{
parts: {
part1: Multipart::field({name:"myFirstPart",value: firstPart}),
part2: Multipart::field("mySecondPart", secondPart)
}
}
1
2
3
4
5
6
7
------=_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--
Example
This example produces two parts. The first part (named order
) outputs
content in JSON and provides a file name for the part (order.json
). The
second (named clients
) outputs content in XML and does not provide a file
name. Also notice that in this example you need to add the function’s
namespace to the function name, for example, Multipart::field
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
%dw 2.0
import dw::module::Multipart
output multipart/form-data
var myOrder = [
{
order: 1,
amount: 2
},
{
order: 32,
amount: 1
}
]
var myClients = {
clients: {
client: {
id: 1,
name: "Mariano"
},
client: {
id: 2,
name: "Shoki"
}
}
}
---
{
parts: {
order: Multipart::field({name:"order",value: myOrder, mime: "application/json", fileName: "order.json"}),
clients: Multipart::field({name:"clients", value: myClients, mime: "application/xml"})
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
------=_Part_8032_681891620.1542560124825
Content-Type: application/json
Content-Disposition: form-data; name="order"; filename="order.json"
[
{
"order": 1,
"amount": 2
},
{
"order": 32,
"amount": 1
}
]
------=_Part_8032_681891620.1542560124825
Content-Type: application/xml
Content-Disposition: form-data; name="clients"
<clients>
<client>
<id>1</id>
<name>Mariano</name>
</client>
<client>
<id>2</id>
<name>Shoki</name>
</client>
</clients>
------=_Part_8032_681891620.1542560124825--
field(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 in a comma-separated
list, for example:
1
Multipart::field("order", myOrder,"application/json", "order.json")`
Parameters
Name | Description |
---|---|
opts |
A set of parameters that specify:
|
Example
This example produces two parts. The first part (named order
) outputs
content in JSON and provides a file name for the part (order.json
). The
second (named clients
) outputs content in XML and does not provide a file
name. The only difference between this field
example and the previous
field
example is the way you pass in arguments to the method. Also notice
that in this example you need to add the function’s namespace to the function
name, for example, Multipart::field
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
%dw 2.0
import dw::module::Multipart
output multipart/form-data
var myOrder = [
{
order: 1,
amount: 2
},
{
order: 32,
amount: 1
}
]
var myClients = {
clients: {
client: {
id: 1,
name: "Mariano"
},
client: {
id: 2,
name: "Shoki"
}
}
}
---
{
parts: {
order: Multipart::field("order", myOrder, "application/json", "order.json"),
clients: Multipart::field("clients", myClients, "application/xml")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
------=_Part_4846_2022598837.1542560230901
Content-Type: application/json
Content-Disposition: form-data; name="order"; filename="order.json"
[
{
"order": 1,
"amount": 2
},
{
"order": 32,
"amount": 1
}
]
------=_Part_4846_2022598837.1542560230901
Content-Type: application/xml
Content-Disposition: form-data; name="clients"
<clients>
<client>
<id>1</id>
<name>Mariano</name>
</client>
<client>
<id>2</id>
<name>Shoki</name>
</client>
</clients>
------=_Part_4846_2022598837.1542560230901--
13.1.2. file
file(opts: {| name: String, path: String, mime?: String, fileName?: String |})
Creates a MultipartPart
data structure from a resource file.
This version of the file
function accepts as argument an object containing key/value pairs, enabling you to enter the key/value pairs in any order, for example:
1
Multipart::file({ name: "myFile", path: "myClients.json", mime: "application/json", fileName: "partMyClients.json"})
Parameters
Name | Description |
---|---|
opts |
An object that specifies the following key/value pairs:
|
Example
This example creates a MultipartPart
from a file accessible to the DataWeave function, the file name is orders.xml
and is located in the Mule application’s /src/main/resources
folder.
The file
function locates the external orders.xml
file and uses key/value pairs to indicate the various parameters needed to build the MultipartPart
.
-
The
name
can be anything, but it usually coincides with the required parameter needed by the receiving server that accepts thisMultipart
payload. -
The
path
is set to./orders.xml
, which is the path and name for theorders.xml
file that is loaded into theMultipartPart
. -
The
mime
parameter specifies the correct MIME type for the file. In this case, it isapplication/xml
. -
The
filename
can be changed to any value, it can be different from the actual input file’s filename.
Note that the output of this example is not compatible with the multipart/form-data
output type because it is just one part of a Multipart
structure. To create a valid multipart/form-data
output, use the Multipart::form()
function with one or more Multipart
files and/or fields.
1
2
3
4
5
6
%dw 2.0
import dw::module::Multipart
output application/dw
var ordersFilePath = "./orders.xml"
---
Multipart::file{ name: "file", path: ordersFilePath, mime: "application/xml", fileName: "orders.xml" }
A file called orders.xml
located in src/main/resources
with the following content:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<orders>
<order>
<item>
<id>1001</id>
<qty>1</qty>
<price>\$100</price>
</item>
<item>
<id>2001</id>
<qty>2</qty>
<price>\$50</price>
</item>
</order>
</orders>
1
2
3
4
5
6
7
8
9
10
{
headers: {
"Content-Type": "application/xml",
"Content-Disposition": {
name: "file",
filename: "orders.xml"
}
},
content: "<?xml version='1.0' encoding='UTF-8'?>\n<orders>\n <order>\n <item>\n <id>1001</id>\n <qty>1</qty>\n <price>\$100</price>\n </item>\n <item>\n <id>2001</id>\n <qty>2</qty>\n <price>\$50</price>\n </item>\n </order>\n</orders>"
}
Example
This example inserts file content from a MultipartPart
into a Multipart
, resulting in a multipart/form-data
output. The example uses the form
function to create the Multipart
and uses file
to create a part.
The Multipart::form()
function accepts an array of Multipart
items, where each part can be created using the Multipart::field()
or Multipart::file()
functions.
1
2
3
4
5
6
7
8
9
%dw 2.0
import dw::module::Multipart
output multipart/form-data
var ordersFilePath = "./orders.xml"
var myArgs = { name: "file", path: ordersFilePath, mime: "application/xml", fileName: "myorders.xml"}
---
Multipart::form([
Multipart::file(myArgs)
])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
------=_Part_5349_1228640551.1560391284935
Content-Type: application/xml
Content-Disposition: form-data; name="file"; filename="myorders.xml"
<?xml version='1.0' encoding='UTF-8'?>
<orders>
<order>
<item>
<id>1001</id>
<qty>1</qty>
<price>$100</price>
</item>
<item>
<id>2001</id>
<qty>2</qty>
<price>$50</price>
</item>
</order>
</orders>
------=_Part_5349_1228640551.1560391284935--
file(fieldName: String, path: String, mime: String = 'application/octet-stream', sentFileName: String = 'filename')
Creates a MultipartPart
data structure from a resource file.
This version of the file
function accepts String arguments in a comma-separated
list, for example:
1
Multipart::field("myFile", myClients, 'application/json', "partMyClients.json")
Parameters
Name | Description |
---|---|
|
A unique name (required) for the |
|
A path (required) relative to the |
|
The mime type (optional for strings), for example, |
|
An optional file name value for the |
Example
This example inserts file content from a MultipartPart
into a Multipart
data structure. It uses the form
function to create the Multipart
type
and uses file
to create a part named myClient
with JSON content from
an external file myClients.json
. It also specifies partMyClients.json
as
the value for to the filename
parameter.
1
2
3
4
5
6
7
8
%dw 2.0
import dw::module::Multipart
var myClients = "myClients.json"
output multipart/form-data
---
Multipart::form([
Multipart::file("myFile", myClients, 'application/json', "partMyClients.json")
])
A file called myClients.json
and located in src/main/resources
with the
following content.
1
2
3
4
5
6
7
8
9
10
clients: {
client: {
id: 1,
name: "Mariano"
},
client: {
id: 2,
name: "Shoki"
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
------=_Part_1586_1887987980.1542569342438
Content-Type: application/json
Content-Disposition: form-data; name="myFile"; filename="partMyClients.json"
{
clients: {
client: {
id: 1,
name: "Mariano"
},
client: {
id: 2,
name: "Shoki"
}
}
}
------=_Part_1586_1887987980.1542569342438--
13.1.3. form
form(parts: Array<MultipartPart>): Multipart
Creates a Multipart
data structure using a specified array of parts.
Parameters
Name | Description |
---|---|
parts |
An array of parts ( |
Example
This example creates a Multipart
data structure that contains three parts.
The first part uses the Multipart::file()
function to import an external file named orders.xml
. The file is located in the internal src/main/resources
folder of the Mule application. See the file function documentation for more details on this example.
The second part uses the Multipart::field()
function version that accepts field names as input parameters in the form of an object with key/value pairs, enabling you to pass the keys in any order. This part also does not specify the optional fileName
parameter. When specified, fileName
is part of the Content-Distribution
element of the part. The mime
field is also optional. When included, the field sets the Content-Type
element to the mime
value. In this case the Content-Type
is set to text/plain
.
The third part uses the more compact version of the Multipart::field()
function which sets the required and optional parameters, in the correct order, as input parameters. The first three parameters name
, value
, and mime
are required. The fileName
parameters is optional, use it only if the content is read from a file or is written to a file. In this version, the mime
parameter is output as the Content-Type
element, and the fileName
is output as the filename
parameter of the Content-Distribution
element.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import dw::module::Multipart
output multipart/form-data
var myOrders = "./orders.xml"
var fileArgs = { name: "file", path: myOrders, mime: "application/xml", fileName: "myorders.xml"}
var fieldArgs = {name:"userName",value: "Annie Point", mime: "text/plain"}
---
Multipart::form([
Multipart::file(fileArgs),
Multipart::field(fieldArgs),
Multipart::field("myJson", {"user": "Annie Point"}, "application/json", "userInfo.json")
])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
------=_Part_146_143704079.1560394078604
Content-Type: application/xml
Content-Disposition: form-data; name="file"; filename="myorders.xml"
<?xml version='1.0' encoding='UTF-8'?>
<orders>
<order>
<item>
<id>1001</id>
<qty>1</qty>
<price>$100</price>
</item>
<item>
<id>2001</id>
<qty>2</qty>
<price>$50</price>
</item>
</order>
</orders>
------=_Part_146_143704079.1560394078604
Content-Type: text/plain
Content-Disposition: form-data; name="userName"
Annie Point
------=_Part_146_143704079.1560394078604
Content-Type: application/json
Content-Disposition: form-data; name="myJson"; filename="userInfo.json"
{
"user": "Annie Point"
}
------=_Part_146_143704079.1560394078604--
Example
This example constructs a data structure using DataWeave code that is compatible with the multipart/form-data
output format, demonstrating how you can manually construct a data structure compatible with multipart/form-data
output, without using the form
function.
In the following structure, the part keys part1
and part2
are stripped out in the multipart/form-data
output.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import dw::module::Multipart
output multipart/form-data
var firstPart = "content for my first part"
var secondPart = "content for my second part"
---
{
parts: {
part1: Multipart::field({name:"myFirstPart",value: firstPart}),
part2: Multipart::field("mySecondPart", secondPart)
}
}
1
2
3
4
5
6
7
8
9
------=_Part_320_1528378161.1542639222352
Content-Disposition: form-data; name="myFirstPart"
content for my first part
------=_Part_320_1528378161.1542639222352
Content-Disposition: form-data; name="mySecondPart"
content for my second part
------=_Part_320_1528378161.1542639222352--
13.1.4. generateBoundary
generateBoundary(len: Number = 70): String
Helper function for generating boundaries in Multipart
data structures.
13.2. Types
13.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 } }
13.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 }
14. dw::Runtime
This module contains functions for interacting with the DataWeave runtime, which executes the language.
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.
14.1. Functions
14.1.1. dataFormatsDescriptor
dataFormatsDescriptor(): Array<DataFormatDescriptor>
Returns an array of all DataFormatDescriptor
values that are installed in
the current instance of DataWeave.
Example
This example shows how dataFormatsDescriptor
behaves with different inputs.
1
2
3
import * from dw::Runtime
---
dataFormatsDescriptor()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
[
{
"id": "json",
"binary": false,
"defaultEncoding": "UTF-8",
"extensions": [
".json"
],
"defaultMimeType": "application/json",
"acceptedMimeTypes": [
"application/json"
],
"readerProperties": [
{
"name": "streaming",
"optional": true,
"defaultValue": false,
"description": "Used for streaming input (use only if entries are accessed sequentially).",
"possibleValues": [
true,
false
]
}
],
"writerProperties": [
{
"name": "writeAttributes",
"optional": true,
"defaultValue": false,
"description": "Indicates that if a key has attributes, they are going to be added as children key-value pairs of the key that contains them. The attribute new key name will start with @.",
"possibleValues": [
true,
false
]
},
{
"name": "skipNullOn",
"optional": true,
"defaultValue": "None",
"description": "Indicates where is should skips null values if any or not. By default it doesn't skip.",
"possibleValues": [
"arrays",
"objects",
"everywhere"
]
}
]
},
{
"id": "xml",
"binary": false,
"extensions": [
".xml"
],
"defaultMimeType": "application/xml",
"acceptedMimeTypes": [
"application/xml"
],
"readerProperties": [
{
"name": "supportDtd",
"optional": true,
"defaultValue": true,
"description": "Whether DTD handling is enabled or disabled; disabling means both internal and external subsets will just be skipped unprocessed.",
"possibleValues": [
true,
false
]
},
{
"name": "streaming",
"optional": true,
"defaultValue": false,
"description": "Used for streaming input (use only if entries are accessed sequentially).",
"possibleValues": [
true,
false
]
},
{
"name": "maxEntityCount",
"optional": true,
"defaultValue": 1,
"description": "The maximum number of entity expansions. The limit is in place to avoid Billion Laughs attacks.",
"possibleValues": [
]
}
],
"writerProperties": [
{
"name": "writeDeclaration",
"optional": true,
"defaultValue": true,
"description": "Indicates whether to write the XML header declaration or not.",
"possibleValues": [
true,
false
]
},
{
"name": "indent",
"optional": true,
"defaultValue": true,
"description": "Indicates whether to indent the code for better readability or to compress it into a single line.",
"possibleValues": [
true,
false
]
}
]
}
]
14.1.2. eval
eval(fileToExecute: String, fs: Dictionary<String>, readerInputs: Dictionary<ReaderInput> = {}, inputValues: Dictionary<Any> = {}, configuration: RuntimeExecutionConfiguration = {}): EvalSuccess | ExecutionFailure
Evaluates a script with the specified context and returns the result of that evaluation.
Parameters
Name | Description |
---|---|
fileToExecute |
Name of the file to execute. |
fs |
An object that contains the file to evaluate. |
readerInputs |
Reader inputs to bind. |
inputValues |
Additional literal values to bind |
configuration |
The runtime configuration. |
Example
This example shows how eval
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
%dw 2.0
import * from dw::Runtime
var jsonValue = {
value: '{"name": "Mariano"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var jsonValue2 = {
value: '{"name": "Mariano", "lastName": "achaval"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var invalidJsonValue = {
value: '{"name": "Mariano' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var Utils = "fun sum(a,b) = a +b"
output application/json
---
{
"execute_ok" : run("main.dwl", {"main.dwl": "{a: 1}"}, {"payload": jsonValue }),
"logs" : do {
var execResult = run("main.dwl", {"main.dwl": "{a: log(1)}"}, {"payload": jsonValue })
---
{
m: execResult.logs.message,
l: execResult.logs.level
}
},
"grant" : eval("main.dwl", {"main.dwl": "{a: readUrl(`http://google.com`)}"}, {"payload": jsonValue }, {},{ securityManager: (grant, args) -> false }),
"library" : eval("main.dwl", {"main.dwl": "Utils::sum(1,2)", "/Utils.dwl": Utils }, {"payload": jsonValue }),
"timeout" : eval("main.dwl", {"main.dwl": "(1 to 1000000000000) map \$ + 1" }, {"payload": jsonValue }, {},{timeOut: 2}).success,
"execFail" : eval("main.dwl", {"main.dwl": "dw::Runtime::fail('My Bad')" }, {"payload": jsonValue }),
"parseFail" : eval("main.dwl", {"main.dwl": "(1 + " }, {"payload": jsonValue }),
"writerFail" : eval("main.dwl", {"main.dwl": "output application/xml --- 2" }, {"payload": jsonValue }),
"defaultOutput" : eval("main.dwl", {"main.dwl": "payload" }, {"payload": jsonValue2}, {},{outputMimeType: "application/csv", writerProperties: {"separator": "|"}}),
"onExceptionFail": do {
dw::Runtime::try( () ->
eval("main.dwl", {"main.dwl": "dw::Runtime::fail('Failing Test')" }, {"payload": jsonValue2}, {},{onException: "FAIL"})
).success
},
"customLogger":
eval(
"main.dwl",
{"main.dwl": "log(1234)" },
{"payload": jsonValue2},
{},
{
loggerService: {
initialize: () -> {token: "123"},
log: (level, msg, context) -> log("$(level) $(msg)", context)
}
}
)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
{
"execute_ok": {
"success": true,
"value": "{\n a: 1\n}",
"mimeType": "application/dw",
"encoding": "UTF-8",
"logs": [
]
},
"logs": {
"m": [
"1"
],
"l": [
"INFO"
]
},
"grant": {
"success": false,
"message": "The given required permissions: `Resource` are not being granted for this execution.\nTrace:\n at readUrl (Unknown)\n at main::main (line: 1, column: 5)",
"location": {
"start": {
"index": 0,
"line": 0,
"column": 0
},
"end": {
"index": 0,
"line": 0,
"column": 0
},
"content": "Unknown location"
},
"stack": [
"readUrl (anonymous:0:0)",
"main (main:1:5)"
],
"logs": [
]
},
"library": {
"success": true,
"value": 3,
"logs": [
]
},
"timeout": true,
"execFail": {
"success": false,
"message": "My Bad\nTrace:\n at fail (Unknown)\n at main::main (line: 1, column: 1)",
"location": {
"start": {
"index": 0,
"line": 0,
"column": 0
},
"end": {
"index": 0,
"line": 0,
"column": 0
},
"content": "Unknown location"
},
"stack": [
"fail (anonymous:0:0)",
"main (main:1:1)"
],
"logs": [
]
},
"parseFail": {
"success": false,
"message": "Invalid input \"1 + \", expected parameter or parenEnd (line 1, column 2):\n\n\n1| (1 + \n ^^^^\nLocation:\nmain (line: 1, column:2)",
"location": {
"start": {
"index": 0,
"line": 1,
"column": 2
},
"end": {
"index": 4,
"line": 1,
"column": 6
},
"content": "\n1| (1 + \n ^^^^"
},
"logs": [
]
},
"writerFail": {
"success": true,
"value": 2,
"logs": [
]
},
"defaultOutput": {
"success": true,
"value": {
"name": "Mariano",
"lastName": "achaval"
},
"logs": [
]
},
"onExceptionFail": false,
"customLogger": {
"success": true,
"value": 1234,
"logs": [
]
}
}
14.1.3. evalUrl
evalUrl(url: String, readerInputs: Dictionary<ReaderInput> = {}, inputValues: Dictionary<Any> = {}, configuration: RuntimeExecutionConfiguration = {}): EvalSuccess | ExecutionFailure
Evaluates the script at the specified URL.
Parameters
Name | Description |
---|---|
url |
Name of the file execute. |
readerInputs |
Inputs to read and bind to the execution. |
inputValues |
Inputs to bind directly to the execution. |
configuration |
The runtime configuration. |
Example
This example shows how evalUrl
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
%dw 2.0
import * from dw::Runtime
var jsonValue = {
value: '{"name": "Mariano"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var Utils = "fun sum(a,b) = a +b"
output application/json
---
{
"execute_ok" : evalUrl("classpath://org/mule/weave/v2/engine/runtime_evalUrl/example.dwl", {"payload": jsonValue }),
"execute_ok_withValue" : evalUrl("classpath://org/mule/weave/v2/engine/runtime_evalUrl/example.dwl", {}, {"payload": {name: "Mariano"}})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"execute_ok": {
"success": true,
"value": "Mariano",
"logs": [
]
},
"execute_ok_withValue": {
"success": true,
"value": "Mariano",
"logs": [
]
}
}
14.1.4. fail
fail(message: String = 'Error'): Nothing
Throws an exception with the specified message.
Parameters
Name | Description |
---|---|
message |
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.
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
...
14.1.5. failIf
failIf<T>(value: T, evaluator: (value: T) -> Boolean, message: String = 'Failed'): T
Produces an error with the specified message if the expression in
the evaluator returns true
. Otherwise, the function returns the value.
Parameters
Name | Description |
---|---|
value |
The value to return only if the |
evaluator |
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
14.1.6. location
location(value: Any): Location
Returns the location of a given value, or null
if the
location can’t be traced back to a DataWeave file.
Parameters
Name | Description |
---|---|
value |
A value of any type. |
Example
This example returns the location that defines
the function sqrt
in the dw::Core
module.
1
2
3
4
5
%dw 2.0
import location from dw::Runtime
output application/json
---
location(sqrt)
1
2
3
4
5
6
7
8
{
"uri": "/dw/Core.dwl",
"nameIdentifier": "dw::Core",
"startLine": 5797,
"startColumn": 36,
"endLine": 5797,
"endColumn": 77
}
14.1.7. locationString
locationString(value: Any): String
Returns the location string of a given value.
Parameters
Name | Description |
---|---|
value |
A value of any type. |
Example
This example returns the contents of the line (the location) that defines
variable a
in the header of the DataWeave script.
1
2
3
4
5
6
%dw 2.0
import * from dw::Runtime
var a = 123
output application/json
---
locationString(a)
1
"var a = 123"
14.1.8. orElse
orElse<T, R>(previous: TryResult<T>, orElse: () -> R): T | R
Returns the result of the orElse
argument if the previous
argument to
try
fails. Otherwise, the function returns the value of the previous
argument.
Parameters
Name | Description |
---|---|
previous |
Result from a previous call to |
orElse |
Argument to return if the |
Example
This example waits shows how to chain different try
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::Runtime
var user = {}
var otherUser = {name: "DW"}
output application/json
---
{
a: try(() -> user.name!) orElse "No User Name",
b: try(() -> otherUser.name) orElse "No User Name"
}
1
2
3
4
{
"a": "No User Name",
"b": "DW"
}
14.1.9. orElseTry
orElseTry<T, R>(previous: TryResult<T>, orElse: () -> R): TryResult<T | R>
Function to use with try
to chain multiple try
requests.
Parameters
Name | Description |
---|---|
previous |
Result from a previous call to |
orElseTry |
Argument to try if the |
Example
This example waits shows how to chain different try
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::Runtime
var user = {}
var otherUser = {}
output application/json
---
{
a: try(() -> user.name!) orElseTry otherUser.name!,
b: try(() -> user.name!) orElseTry "No User Name"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"a": {
"success": false,
"error": {
"kind": "KeyNotFoundException",
"message": "There is no key named 'name'",
"location": "\n9| a: try(() -> user.name!) orElseTry otherUser.name!,\n ^^^^^^^^^^^^^^",
"stack": [
"main (org::mule::weave::v2::engine::transform:9:40)"
]
}
},
"b": {
"success": true,
"result": "No User Name"
}
}
14.1.10. prop
prop(propertyName: String): String | Null
Returns the value of the property with the specified name or null
if the
property is not defined.
Parameters
Name | Description |
---|---|
propertyName |
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"} }
14.1.11. props
props(): Dictionary<String>
Returns all the properties configured for the DataWeave runtime, which executes the language.
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"}
14.1.12. run
run(fileToExecute: String, fs: Dictionary<String>, readerInputs: Dictionary<ReaderInput> = {}, inputValues: Dictionary<Any> = {}, configuration: RuntimeExecutionConfiguration = {}): RunSuccess | ExecutionFailure
Runs the input script under the provided context and executes the script in the current runtime.
Parameters
Name | Description |
---|---|
fileToExecute |
Name of the file to execute. |
fs |
File system that contains the file to execute. |
readerInput |
Inputs to read and bind to the execution. |
inputValues |
Inputs to bind directly to the execution. |
configuration |
The runtime configuration. |
Example
This example shows how run
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import * from dw::Runtime
var jsonValue = {
value: '{"name": "Mariano"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var jsonValue2 = {
value: '{"name": "Mariano", "lastName": "achaval"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var invalidJsonValue = {
value: '{"name": "Mariano' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var Utils = "fun sum(a,b) = a +b"
---
{
"execute_ok" : run("main.dwl", {"main.dwl": "{a: 1}"}, {"payload": jsonValue }),
"logs" : do {
var execResult = run("main.dwl", {"main.dwl": "{a: log(1)}"}, {"payload": jsonValue })
---
{
m: execResult.logs.message,
l: execResult.logs.level
}
},
"grant" : run("main.dwl", {"main.dwl": "{a: readUrl(`http://google.com`)}"}, {"payload": jsonValue }, { securityManager: (grant, args) -> false }),
"library" : run("main.dwl", {"main.dwl": "Utils::sum(1,2)", "/Utils.dwl": Utils }, {"payload": jsonValue }),
"timeout" : run("main.dwl", {"main.dwl": "(1 to 1000000000000) map \$ + 1" }, {"payload": jsonValue }, {timeOut: 2}).success,
"execFail" : run("main.dwl", {"main.dwl": "dw::Runtime::fail('My Bad')" }, {"payload": jsonValue }),
"parseFail" : run("main.dwl", {"main.dwl": "(1 + " }, {"payload": jsonValue }),
"writerFail" : run("main.dwl", {"main.dwl": "output application/xml --- 2" }, {"payload": jsonValue }),
"readerFail" : run("main.dwl", {"main.dwl": "output application/xml --- payload" }, {"payload": invalidJsonValue }),
"defaultOutput" : run("main.dwl", {"main.dwl": "payload" }, {"payload": jsonValue2}, {outputMimeType: "application/csv", writerProperties: {"separator": "|"}}),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
{
"execute_ok": {
"success": true,
"value": "{\n a: 1\n}",
"mimeType": "application/dw",
"encoding": "UTF-8",
"logs": [
]
},
"logs": {
"m": [
"1"
],
"l": [
"INFO"
]
},
"grant": {
"success": false,
"message": "The given required permissions: `Resource` are not being granted for this execution.\nTrace:\n at readUrl (Unknown)\n at main::main (line: 1, column: 5)",
"location": {
"start": {
"index": 0,
"line": 0,
"column": 0
},
"end": {
"index": 0,
"line": 0,
"column": 0
},
"content": "Unknown location"
},
"stack": [
"readUrl (anonymous:0:0)",
"main (main:1:5)"
],
"logs": [
]
},
"library": {
"success": true,
"value": "3",
"mimeType": "application/dw",
"encoding": "UTF-8",
"logs": [
]
},
"timeout": false,
"execFail": {
"success": false,
"message": "My Bad\nTrace:\n at fail (Unknown)\n at main::main (line: 1, column: 1)",
"location": {
"start": {
"index": 0,
"line": 0,
"column": 0
},
"end": {
"index": 0,
"line": 0,
"column": 0
},
"content": "Unknown location"
},
"stack": [
"fail (anonymous:0:0)",
"main (main:1:1)"
],
"logs": [
]
},
"parseFail": {
"success": false,
"message": "Invalid input \"1 + \", expected parameter or parenEnd (line 1, column 2):\n\n\n1| (1 + \n ^^^^\nLocation:\nmain (line: 1, column:2)",
"location": {
"start": {
"index": 0,
"line": 1,
"column": 2
},
"end": {
"index": 4,
"line": 1,
"column": 6
},
"content": "\n1| (1 + \n ^^^^"
},
"logs": [
]
},
"writerFail": {
"success": false,
"message": "Trying to output non-whitespace characters outside main element tree (in prolog or epilog), while writing Xml at .",
"location": {
"content": ""
},
"stack": [
],
"logs": [
]
},
"readerFail": {
"success": false,
"message": "Unexpected end-of-input at payload@[1:18] (line:column), expected '\"', while reading `payload` as Json.\n \n1| {\"name\": \"Mariano\n ^",
"location": {
"content": "\n1| {\"name\": \"Mariano\n ^"
},
"stack": [
],
"logs": [
]
},
"defaultOutput": {
"success": true,
"value": "name|lastName\nMariano|achaval\n",
"mimeType": "application/csv",
"encoding": "UTF-8",
"logs": [
]
}
}
14.1.13. runUrl
runUrl(url: String, readerInputs: Dictionary<ReaderInput> = {}, inputValues: Dictionary<Any> = {}, configuration: RuntimeExecutionConfiguration = {}): RunSuccess | ExecutionFailure
Runs the script at the specified URL.
Parameters
Name | Description |
---|---|
url |
The name of the file to execute. |
readerInputs |
Inputs to read and bind to the execution. |
inputValues |
Inputs to be bind directly to the execution. |
configuration |
The runtime configuration. |
Example
This example shows how runUrl
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
import * from dw::Runtime
var jsonValue = {
value: '{"name": "Mariano"}' as Binary {encoding: "UTF-8"},
encoding: "UTF-8",
properties: {},
mimeType: "application/json"
}
var Utils = "fun sum(a,b) = a +b"
---
{
"execute_ok" : runUrl("classpath://org/mule/weave/v2/engine/runtime_runUrl/example.dwl", {"payload": jsonValue })
}
1
2
3
4
5
6
7
8
9
10
11
{
"execute_ok": {
"success": true,
"value": "\"Mariano\"",
"mimeType": "application/dw",
"encoding": "UTF-8",
"logs": [
]
}
}
14.1.14. try
try<T>(delegate: () -> T): TryResult<T>
Evaluates the delegate function and returns an object with success: true
and result
if the delegate function succeeds, or an object with success: false
and error
if the delegate function throws an exception.
The orElseTry
and orElse
functions will also continue processing if the try
function fails. See the orElseTry
and orElse
documentation for more complete examples of handling failing try
function expressions.
Note: Instead of using the orElseTry
and orElse
functions, based on the output of the try
function, you can add conditional logic to execute when the result is success: true
or success: false
.
Parameters
Name | Description |
---|---|
delegate |
The function to evaluate. |
Example
This example calls the try
function using the randomNumber
function as argument.
The function randomNumber
generates a random number and calls fail
if the number is greater than 0.5. The declaration of this function is in the script’s header.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import try, fail from dw::Runtime
output application/json
fun randomNumber() =
if(random() > 0.5)
fail("This function is failing")
else
"OK"
---
try(() -> randomNumber())
When randomNumber
fails, the output is:
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"success": false,
"error": {
"kind": "UserException",
"message": "This function is failing",
"location": "Unknown location",
"stack": [
"fail (anonymous:0:0)",
"myFunction (anonymous:1:114)",
"main (anonymous:1:179)"
]
}
}
When randomNumber
succeeds, the output is:
1
2
3
4
{
"success": true,
"result": "OK"
}
14.1.15. version
version(): String
Returns the DataWeave version that is currently running.
Example
This example returns the DataWeave version.
1
2
3
4
5
%dw 2.0
import * from dw::Runtime
output application/json
---
version()
1
"2.5"
14.1.16. wait
wait<T>(value: T, timeout: Number): T
Stops the execution for the specified timeout period (in milliseconds).
Stopping the execution blocks the thread, potentially causing slowness, low performance and potentially freezing of the entire runtime. This operation is intended for limited functional testing purposes. Do not use this function in a production application, performance testing, or with multiple applications deployed. |
Parameters
Name | Description |
---|---|
value |
Input of any type. |
timeout |
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 }
14.2. Types
14.2.1. DataFormatDescriptor
Description of a DataFormat
that provides all metadata information.
1
{ name: String, binary: Boolean, defaultEncoding?: String, extensions: Array<String>, defaultMimeType: String, acceptedMimeTypes: Array<String>, readerProperties: Array<DataFormatProperty>, writerProperties: Array<DataFormatProperty> }
14.2.2. DataFormatProperty
Type that describes a data format property. The fields include a name
,
description
, array of possible values (possibleValues
), an optional default
value (defaultValue
), and an optional
flag that indicates whether the property
is required or not.
1
{ name: String, optional: Boolean, defaultValue?: Any, description: String, possibleValues: Array<Any> }
14.2.3. EvalSuccess
Data type of the data that returns when an eval
function executes successfully.
1
{ success: true, value: Any, logs: Array<LogEntry> }
14.2.4. ExecutionFailure
Data type of the data that returns when a run
or eval
function fails.
1
{ success: false, message: String, kind: String, stack?: Array<String>, location: Location, logs: Array<LogEntry> }
14.2.5. Location
Type that represents the location of an expression in a DataWeave file.
1
{ start?: Position, end?: Position, locationString: String, text?: String, sourceIdentifier?: String }
14.2.6. LogEntry
Type for a log entry, which consists of a level
for a LogLevel
value,
a timestamp
, and message
.
1
{ level: LogLevel, timestamp: String, message: String }
14.2.7. LogLevel
Identifies the different kinds of log levels (INFO
, ERROR
, or WARN
).
1
"INFO" | "ERROR" | "WARN"
14.2.8. LoggerService
Service that handles all logging:
-
initialize
: Function called when the execution starts. DataWeave sends the result to everylog
call through thecontext
parameter, so that, for example, a logging header can be sent at initialization and recovered in each log. -
log
: Function that is called on every log message. -
shutdown
: Function called when the execution completes, which is a common time to flush any buffer or to log out gracefully.
1
{ initialize?: () -> Object, log: (level: LogLevel, msg: String, context: Object) -> Any, shutdown?: () -> Boolean }
14.2.9. MimeType
A String representation of a MIME type.
1
String
14.2.10. Position
Type that represents a position in a file by its index and its line and column.
1
{ index: Number, line: Number, column: Number }
14.2.11. ReaderInput
Input to the DataWeave reader created for the specified MIME type, which includes the Binary input and MIME type, as well as optional encoding and properties values.
-
value
: The input, in Binary format. -
encoding
: The encoding for the reader to use. -
properties
: The reader properties used to parse the input. -
mimeType
: The MIME type of the input.
1
{ value: Binary, encoding?: String, properties?: Dictionary<SimpleType>, mimeType: MimeType }
14.2.12. RunSuccess
Data type of the data that returns when a run
function executes successfully.
1
{ success: true, value: Binary, mimeType: MimeType, encoding?: String, logs: Array<LogEntry> }
14.2.13. RuntimeExecutionConfiguration
Configuration of the runtime execution that has advanced parameters.
-
timeOut
: Maximum amount of time the DataWeave script takes before timing out. -
outputMimeType
: Default output MIME type if not specified in the DataWeave script. -
writerProperties
: Writer properties to use with the specified theoutputMimeType
property. -
onException
Specifies the behavior that occurs when the execution fails:-
HANDLE
(default value) returnsExecutionFailure
. -
FAIL
propagates an exception.
-
-
securityManager
: Identifies theSecurityManager
to use in this execution. This security manager is composed by the currentSecurityManager
. -
loggerService
: TheLoggerService
to use in this execution. -
maxStackSize
: The maximum stack size. -
onUnhandledTimeout
: Callback that is called when the watchdog was not able to stop the execution after a timeout, which is useful for logging or reporting the problem. The callback is called with the following:-
threadName
: Name of the thread that hanged. -
javaStackTrace
: Java stack trace where the hang occurred. -
code
: The DataWeave code that caused the hang.
-
1
{ timeOut?: Number, outputMimeType?: MimeType, writerProperties?: Dictionary<SimpleType>, onException?: "HANDLE" | "FAIL", securityManager?: SecurityManager, loggerService?: LoggerService, maxStackSize?: Number, onUnhandledTimeout?: (threadName: String, javaStackTrace: String, code: String) -> Any }
14.2.14. SecurityManager
Function that is called when a privilege must be granted to the current execution.
-
grant
is the name of the privilege, such asResource
. -
args
provides a list of parameters that the function requesting the privilege calls.
1
(grant: String, args: Array<Any>) -> Boolean
14.2.15. TryResult
Object with a result or error message. If success
is false
, data type provides
the error
. If true
, the data type provides the result
.
Starting in Mule 4.4.0, if the stack is not present, the stackTrace
field is available
with the native Java stack trace.
1
{ success: Boolean, result?: T, error?: { kind: String, message: String, stack?: Array<String>, stackTrace?: String, location?: String } }
15. 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.
15.1. Functions
15.1.1. envVar
envVar(variableName: String): String | Null
Returns an environment variable with the specified name or null
if the
environment variable is not defined.
Parameters
Name | Description |
---|---|
variableName |
String that 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
}
]
15.1.2. envVars
envVars(): Dictionary<String>
Returns all the environment variables defined in the host system as an array of strings.
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" }
16. dw::util::Coercions
This utility module assists with type coercions.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::util::Coercions
to the header of your
DataWeave script.
16.1. Functions
16.1.1. toArray
toArray(@StreamCapable text: String): Array<String>
Splits a String
value into an Array
of characters.
Parameters
Name | Description |
---|---|
text |
The |
Example
This example shows how toArray
behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/json indent=false
---
{
a: toArray(""),
b: toArray("hola")
}
1
{"a": [],"b": ["h","o","l","a"]}
16.1.2. toBinary
toBinary(str: String, encoding: String): Binary
Transform a String
value into a Binary
value
using the specified encoding.
Parameters
Name | Description |
---|---|
str |
The |
encoding |
The encoding to apply to the |
Example
This example shows how toBinary
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
'UTF-16Ex': toBinary("DW", "UTF-16"),
'utf16Ex': toBinary("DW", "utf16"),
'UnicodeBigEx': toBinary("DW", "UnicodeBig"),
'UTF-32Ex': toBinary("DW", "UTF-32"),
'UTF_32Ex': toBinary("DW", "UTF_32")
}
1
2
3
4
5
6
7
{
"UTF-16Ex": "/v8ARABX" as Binary {base: "64"},
utf16Ex: "/v8ARABX" as Binary {base: "64"},
UnicodeBigEx: "/v8ARABX" as Binary {base: "64"},
"UTF-32Ex": "AAAARAAAAFc=" as Binary {base: "64"},
UTF_32Ex: "AAAARAAAAFc=" as Binary {base: "64"}
}
16.1.3. toBoolean
toBoolean(str: String): Boolean
Transform a String
value into a Boolean
value.
Parameters
Name | Description |
---|---|
str |
The |
Example
This example shows how toBoolean
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
a: toBoolean("true"),
b: toBoolean("false"),
c: toBoolean("FALSE"),
d: toBoolean("TrUe")
}
1
2
3
4
5
6
{
"a": true,
"b": false,
"c": false,
"d": true
}
16.1.4. toDate
toDate(str: String, formatters: Array<Formatter>): Date
Transforms a String
value into a Date
value using the first Formatter
that
matches with the given value to transform.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toDate
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Coercions
import * from dw::Runtime
output application/dw
---
{
a: toDate("2023-28-03", [{format: "yyyy/MM/dd"}, {format: "yyyy-dd-MM", locale: "en_US"}]),
b: try(() -> toDate("2023-28-03", [{format: "yyyy/MM/dd"}])).error.message
}
1
2
3
4
{
a: |2023-03-28| as Date {format: "yyyy-dd-MM", locale: "en_US"},
b: "Could not find a valid formatter for '2023-28-03'"
}
toDate(str: String, format: String | Null = null, locale: String | Null = null): Date
Transforms a String
value into a Date
value
and accepts a format and locale.
Parameters
Name | Description |
---|---|
str |
The |
format |
The formatting to use on the |
locale |
Optional ISO 3166 country code to use, such as |
Example
This example shows how toDate
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
a: toDate("2015-10-01"),
b: toDate("2003/10/01","uuuu/MM/dd")
}
1
2
3
4
{
a: |2015-10-01|,
b: |2003-10-01| as Date {format: "uuuu/MM/dd"}
}
16.1.5. toDateOrNull
toDateOrNull(str: String, formatters: Array<Formatter>): Date | Null
Transforms a String
value into a Date
value using the first Formatter
that matches
with the given value to transform.
If none of the Formatter
matches with the given value returns a null
value.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toDateOrNull
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
a: toDateOrNull("2023-28-03", [{format: "yyyy/MM/dd"}, {format: "yyyy-dd-MM", locale: "en_US"}]),
b: toDateOrNull("2023-28-03", [{format: "yyyy/MM/dd"}])
}
1
2
3
4
{
a: |2023-03-28| as Date {format: "yyyy-dd-MM", locale: "en_US"},
b: null
}
16.1.6. toDateTime
toDateTime(str: String, formatters: Array<Formatter>): DateTime
Transforms a String
value into a DateTime
value using the first Formatter
that
matches with the given value to transform.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toDateTime
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Coercions
import * from dw::Runtime
output application/dw
---
{
a: toDateTime("2003-10-01 23:57:59Z", [{format: "uuuu/MM/dd HH:mm:ssz"}, {format: "uuuu-MM-dd HH:mm:ssz"}]),
b: try(() -> toDateTime("2003-10-01 23:57:59Z", [{format: "uuuu/MM/dd HH:mm:ssz"}])).error.message
}
1
2
3
4
{
a: |2003-10-01T23:57:59Z| as DateTime {format: "uuuu-MM-dd HH:mm:ssz"},
b: "Could not find a valid formatter for '2003-10-01 23:57:59Z'"
}
toDateTime(number: Number, unit: MillisOrSecs | Null = null): DateTime
Transforms a Number
value into a DateTime
value
using milliseconds
or seconds
as the unit.
Parameters
Name | Description |
---|---|
number |
The |
unit |
The unit to use for the conversion: |
Example
This example shows how toDateTime
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
fromEpoch: toDateTime(1443743879),
fromMillis: toDateTime(1443743879000, "milliseconds")
}
1
2
3
4
{
fromEpoch: |2015-10-01T23:57:59Z|,
fromMillis: |2015-10-01T23:57:59Z| as DateTime {unit: "milliseconds"}
}
toDateTime(str: String, format: String | Null = null, locale: String | Null = null): DateTime
Transforms a String
value into a DateTime
value
and accepts a format and locale.
Parameters
Name | Description |
---|---|
str |
The |
format |
The formatting to use on the |
locale |
Optional ISO 3166 country code to use, such as |
Example
This example shows how toDateTime
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
a: toDateTime("2015-10-01T23:57:59Z"),
b: toDateTime("2003-10-01 23:57:59Z","uuuu-MM-dd HH:mm:ssz")
}
1
2
3
4
{
a: |2015-10-01T23:57:59Z|,
b: |2003-10-01T23:57:59Z| as DateTime {format: "uuuu-MM-dd HH:mm:ssz"}
}
16.1.7. toDateTimeOrNull
toDateTimeOrNull(str: String, formatters: Array<Formatter>): DateTime | Null
Transforms a String
value into a DateTime
value using the first Formatter
that matches
with the given value to transform.
If none of the Formatter
matches with the given value returns a null
value.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toDateTimeOrNull
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
a: toDateTimeOrNull("2003-10-01 23:57:59Z", [{format: "uuuu/MM/dd HH:mm:ssz"}, {format: "uuuu-MM-dd HH:mm:ssz"}]),
b: toDateTimeOrNull("2003-10-01 23:57:59Z", [{format: "uuuu/MM/dd HH:mm:ssz"}])
}
1
2
3
4
{
a: |2003-10-01T23:57:59Z| as DateTime {format: "uuuu-MM-dd HH:mm:ssz"},
b: null
}
16.1.8. toLocalDateTime
toLocalDateTime(str: String, formatters: Array<Formatter>): LocalDateTime
Transforms a String
value into a LocalDateTime
value using the first Formatter
that
matches with the given value to transform.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toLocalDateTime
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Coercions
import * from dw::Runtime
output application/dw
---
{
a: toLocalDateTime("2003-10-01 23:57:59", [{format: "uuuu/MM/dd HH:mm:ss"}, {format: "uuuu-MM-dd HH:mm:ss"}]),
b: try(() -> toLocalDateTime("2003-10-01 23:57:59", [{format: "uuuu/MM/dd HH:mm:ss"}])).error.message
}
1
2
3
4
{
a: |2003-10-01T23:57:59| as LocalDateTime {format: "uuuu-MM-dd HH:mm:ss"},
b: "Could not find a valid formatter for '2003-10-01 23:57:59'"
}
toLocalDateTime(str: String, format: String | Null = null, locale: String | Null = null): LocalDateTime
Transforms a String
value into a LocalDateTime
value
and accepts a format and locale.
Parameters
Name | Description |
---|---|
str |
The |
format |
The formatting to use on the |
locale |
Optional ISO 3166 country code to use, such as |
Example
This example shows how toLocalDateTime
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
a: toLocalDateTime("2015-10-01T23:57:59"),
b: toLocalDateTime("2003-10-01 23:57:59","uuuu-MM-dd HH:mm:ss")
}
1
2
3
4
{
a: |2015-10-01T23:57:59|,
b: |2003-10-01T23:57:59| as LocalDateTime {format: "uuuu-MM-dd HH:mm:ss"}
}
16.1.9. toLocalDateTimeOrNull
toLocalDateTimeOrNull(str: String, formatters: Array<Formatter>): LocalDateTime | Null
Transforms a String
value into a LocalDateTime
value using the first Formatter
that matches
with the given value to transform.
If none of the Formatter
matches with the given value returns a null
value.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toLocalDateTimeOrNull
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
a: toLocalDateTimeOrNull("2003-10-01 23:57:59", [{format: "uuuu/MM/dd HH:mm:ss"}, {format: "uuuu-MM-dd HH:mm:ss"}]),
b: toLocalDateTimeOrNull("2003-10-01 23:57:59", [{format: "uuuu/MM/dd HH:mm:ss"}])
}
1
2
3
4
{
a: |2003-10-01T23:57:59| as LocalDateTime {format: "uuuu-MM-dd HH:mm:ss"},
b: null
}
16.1.10. toLocalTime
toLocalTime(str: String, formatters: Array<Formatter>): LocalTime
Transforms a String
value into a LocalTime
value using the first Formatter
that
matches with the given value to transform.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toLocalTime
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Coercions
import * from dw::Runtime
output application/dw
---
{
a: toLocalTime("23:57:59", [{format: "HH:mm:ss.n"}, {format: "HH:mm:ss"}]),
b: try(() -> toLocalTime("23:57:59", [{format: "HH:mm:ss.n"}])).error.message
}
1
2
3
4
{
a: |23:57:59| as LocalTime {format: "HH:mm:ss"},
b: "Could not find a valid formatter for '23:57:59'"
}
toLocalTime(str: String, format: String | Null = null, locale: String | Null = null): LocalTime
Transforms a String
value into a LocalTime
value
and accepts a format and locale.
Parameters
Name | Description |
---|---|
str |
The |
format |
The formatting to use on the |
locale |
Optional ISO 3166 country code to use, such as |
Example
This example shows how toLocalTime
behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
toLocalTimeEx: toLocalTime("23:57:59"),
toLocalTimeEx2: toLocalTime("13:44:12.283","HH:mm:ss.n")
}
1
2
3
4
{
"toLocalTimeEx": "23:57:59",
"toLocalTimeEx2": "13:44:12.283"
}
16.1.11. toLocalTimeOrNull
toLocalTimeOrNull(str: String, formatters: Array<Formatter>): LocalTime | Null
Transforms a String
value into a LocalTime
value using the first Formatter
that matches
with the given value to transform.
If none of the Formatter
matches with the given value returns a null
value.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toLocalTimeOrNull
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
a: toLocalTimeOrNull("23:57:59", [{format: "HH:mm:ss.n"}, {format: "HH:mm:ss"}]),
b: toLocalTimeOrNull("23:57:59", [{format: "HH:mm:ss.n"}])
}
1
2
3
4
{
a: |23:57:59| as LocalTime {format: "HH:mm:ss"},
b: null
}
16.1.12. toNumber
toNumber(str: String, formatters: Array<Formatter>): Number
Transforms a String
value into a Number
value using the first Formatter
that
matches with the given value to transform.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<DatesFormatter> |
The |
Example
This example shows how toNumber
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Coercions
import * from dw::Runtime
output application/dw
---
{
a: toNumber("0.005", [{format: "seconds"}, {format: ".00"}]),
b: try(() -> toNumber("0.005", [{format: "seconds"}])).error.message
}
1
2
3
4
{
a: 0.005 as Number {format: ".00"},
b: "Could not find a valid formatter for '0.005'"
}
toNumber(dateTime: DateTime, unit: MillisOrSecs | Null = null): Number
A variant of toNumber
that transforms a DateTime
value
into a number of seconds or milliseconds, depending on the
selected unit.
Parameters
Name | Description |
---|---|
dateTime |
The |
unit |
The unit of time ( |
Example
This example shows how toNumber
behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
epoch: toNumber(|2015-10-01T23:57:59Z|),
millis: toNumber(|2015-10-01T23:57:59Z|, "milliseconds")
}
1
2
3
4
{
"epoch": 1443743879,
"millis": 1443743879000
}
toNumber(period: Period, unit: PeriodUnits | Null = null): Number
A variant of toNumber
that transforms a Period
value
into a number of hours, minutes, seconds, milliseconds
or nanoseconds (nanos
).
Parameters
Name | Description |
---|---|
period |
The |
unit |
The unit to apply to the specified |
Example
This example shows how toNumber
behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
toSecondsEx1: toNumber(|PT1H10M|, "seconds"),
toSecondsEx2: toNumber(|PT1M7S|, "milliseconds")
}
1
2
3
4
{
"toSecondsEx1": 4200,
"toSecondsEx2": 67000
}
toNumber(value: String | Key, format: String | Null = null, locale: String | Null = null): Number
A variant of toNumber
that transforms a String
or Key
value into
a Number
value and that accepts a format and locale.
Parameters
Name | Description |
---|---|
value |
The |
format |
Optional formatting to apply to the |
locale |
Optional ISO 3166 country code to use, such as |
Example
This example shows how toNumber
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import * from dw::util::Coercions
var myKey = keysOf({"123" : "myValue"})
output application/json
---
{
"default": toNumber("1.0"),
"withFormat": toNumber("0.005",".00"),
"withLocal": toNumber("1,25","#.##","ES"),
"withExtraPlaceholders": toNumber("5.55","####.####"),
"keyToNumber": toNumber(myKey[0])
}
1
2
3
4
5
6
7
{
"default": 1.0,
"withFormat": 0.005,
"withLocal": 1.25,
"withExtraPlaceholders": 5.55,
"keyToNumber": 123
}
16.1.13. toNumberOrNull
toNumberOrNull(str: String, formatters: Array<Formatter>): Number | Null
Transforms a String
value into a Number
value using the first Formatter
that matches
with the given value to transform.
If none of the Formatter
matches with the given value returns a null
value.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toNumberOrNull
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
a: toNumberOrNull("0.005", [{format: "seconds"}, {format: ".00"}]),
b: toNumberOrNull("0.005", [{format: "seconds"}])
}
1
2
3
4
{
a: 0.005 as Number {format: ".00"},
b: null
}
16.1.14. toPeriod
toPeriod(str: String): Period
Transform a String
value into a Period
value.
Parameters
Name | Description |
---|---|
str |
The |
Example
This example shows how toPeriod
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
toPeriodEx1: toPeriod("P1D"),
toPeriodEx2: toPeriod("PT1H1M")
}
1
2
3
4
{
toPeriodEx1: |P1D|,
toPeriodEx2: |PT1H1M|
}
16.1.15. toRegex
toRegex(str: String): Regex
Transforms a String
value into a Regex
value.
Parameters
Name | Description |
---|---|
str |
The |
Example
This example shows how toRegex
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
toRegexEx1: toRegex("a-Z"),
toRegexEx2: toRegex("0-9+")
}
1
2
3
4
{
toRegexEx1: /a-Z/,
toRegexEx2: /0-9+/
}
16.1.16. toString
toString(number: Number, format: String | Null = null, locale: String | Null = null, roundMode: RoundingMode | Null = null): String
A variant of toString
that transforms a Number
value
(whole or decimal) into a String
value and accepts a
format, locale, and rounding mode value.
Parameters
Name | Description |
---|---|
number |
The |
format |
The formatting to apply to the |
locale |
Optional ISO 3166 country code to use, such as |
roundMode |
Optional parameter for rounding decimal values
when the formatting presents a rounding choice,
such as a format of
|
Example
This example shows how toString
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
a: toString(1.0),
b: toString(0.005,".00"),
c: toString(0.035,"#.##","ES"),
d: toString(0.005,"#.##","ES","HALF_EVEN"),
e: toString(0.035,"#.00",null,"HALF_EVEN"),
f: toString(1.1234,"\$.## 'in my account'")
}
1
2
3
4
5
6
7
8
{
"a": "1",
"b": ".01",
"c": "0,04",
"d": "0",
"e": ".04",
"f": "$1.12 in my account"
}
toString(date: Date | DateTime | LocalDateTime | LocalTime | Time, format: String | Null = null, locale: String | Null = null): String
A variant of toString
that transforms a Date
, DateTime
,
LocalTime
, LocalDateTime
, or Time
value into a String
value.
Parameters
Name | Description |
---|---|
date |
The |
format |
The ISO-8601 formatting to use on the date or time.
For example, this parameter accepts character patterns
patterns based on the Java 8
|
locale |
Optional ISO 3166 country code to use, such as |
Example
This example shows how toString
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
aDate: toString(|2003-10-01|, "uuuu/MM/dd"),
aDateTime: toString(|2018-09-17T22:13:00-03:00|),
aLocalTime: toString(|23:57:59|, "HH-mm-ss"),
aLocalDateTime : toString(|2015-10-01T23:57:59|),
aLocalDateTimeFormatted: toString(|2003-10-01T23:57:59|, "uuuu-MM-dd HH:mm:ss a"),
aLocalDateTimeFormattedAndLocalizedSpain: toString(|2003-01-01T23:57:59|, "eeee, dd MMMM, uuuu HH:mm:ss a", "ES"),
aTime: typeOf(|22:10:18Z|),
aTimeZone: toString(|-03:00|)
}
1
2
3
4
5
6
7
8
9
10
{
"aDate": "2003/10/01",
"aDateTime": "2018-09-17T22:13:00-03:00",
"aLocalTime": "23-57-59",
"aLocalDateTime": "2015-10-01T23:57:59",
"aLocalDateTimeFormatted": "2003-10-01 23:57:59 PM",
"aLocalDateTimeFormattedAndLocalizedSpain": "miércoles, 01 enero, 2003 23:57:59 p. m.",
"aTime": "Time",
"aTimeZone": "-03:00"
}
toString(binary: Binary, encoding: String): String
A variant of toString
that transforms a Binary
value
into a String
value with the specified encoding.
Parameters
Name | Description |
---|---|
binary |
The |
encoding |
The encoding to apply to the |
Example
This example shows how toString
behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
var binaryData= "DW Test" as Binary {encoding: "UTF-32"}
output application/json
---
{
a: toString(binaryData, "UTF-32"),
}
1
2
3
{
"a": "DW Test"
}
toString(data: TimeZone | Uri | Boolean | Period | Regex | Key): String
A variant of toString
that transforms a TimeZone
, Uri
,
Boolean
, Period
, Regex
, or Key
value into a
string.
Parameters
Name | Description |
---|---|
data |
The |
Example
This example shows how toString
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
transformTimeZone: toString(|Z|),
transformBoolean: toString(true),
transformPeriod: toString(|P1D|),
transformRegex: toString(/a-Z/),
transformPeriod: toString(|PT8M10S|),
transformUri: toString("https://docs.mulesoft.com/" as Uri)
} ++
{ transformKey : toString((keysOf({ "aKeyToString" : "aValue"})[0])) }
1
2
3
4
5
6
7
8
9
{
"transformTimeZone": "Z",
"transformBoolean": "true",
"transformPeriod": "P1D",
"transformRegex": "a-Z",
"transformPeriod": "PT8M10S",
"transformUri": "https://docs.mulesoft.com/",
"transformKey": "aKeyToString"
}
toString(arr: Array<String>): String
A variant of toString
that joins an Array
of characters
into a single String
value.
Parameters
Name | Description |
---|---|
arr |
The |
Example
This example shows how toString
behaves with different inputs.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
a: toString([]),
b: toString(["h", "o", "l", "a"])
}
1
2
3
4
{
"a": "",
"b": "hola"
}
16.1.17. toTime
toTime(str: String, formatters: Array<Formatter>): Time
Transforms a String
value into a Time
value using the first Formatter
that
matches with the given value to transform.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toTime
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Coercions
import * from dw::Runtime
output application/dw
---
{
a: toTime("13:44:12.283-08:00", [{format: "HH:mm:ss.xxx"}, {format: "HH:mm:ss.nxxx"}]),
b: try(() -> toTime("13:44:12.283-08:00", [{format: "HH:mm:ss.xxx"}]).error.message
}
1
2
3
4
{
a: |13:44:12.000000283-08:00| as Time {format: "HH:mm:ss.nxxx"},
b: "Could not find a valid formatter for '13:44:12.283-08:00'"
}
toTime(str: String, format: String | Null = null, locale: String | Null = null): Time
Transforms a String
value into a Time
value
and accepts a format and locale.
Parameters
Name | Description |
---|---|
str |
The |
format |
The formatting to use on the |
locale |
Optional ISO 3166 country code to use, such as |
Example
This example shows how toTime
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
a: toTime("23:57:59Z"),
b: toTime("13:44:12.283-08:00","HH:mm:ss.nxxx")
}
1
2
3
4
{
a: |23:57:59Z|,
b: |13:44:12.000000283-08:00| as Time {format: "HH:mm:ss.nxxx"}
}
16.1.18. toTimeOrNull
toTimeOrNull(str: String, formatters: Array<Formatter>): Time | Null
Transforms a String
value into a Time
value using the first Formatter
that matches
with the given value to transform.
If none of the Formatter
matches with the given value returns a null
value.
Parameters
Name | Type | Description |
---|---|---|
|
String |
The |
|
Array<Formatter> |
The |
Example
This example shows how toTimeOrNull
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
a: toTimeOrNull("13:44:12.283-08:00", [{format: "HH:mm:ss.xxx"}, {format: "HH:mm:ss.nxxx"}]),
b: toTimeOrNull("13:44:12.283-08:00", [{format: "HH:mm:ss.xxx"}])
}
1
2
3
4
{
a: |13:44:12.000000283-08:00| as Time {format: "HH:mm:ss.nxxx"},
b: null
}
16.1.19. toTimeZone
toTimeZone(str: String): TimeZone
Transform a String
value into a TimeZone
value.
Parameters
Name | Description |
---|---|
str |
The |
Example
This example shows how toTimeZone
behaves with different inputs.
It produces output in the application/dw
format.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Coercions
output application/dw
---
{
toTimeZoneOffset: toTimeZone("-03:00"),
toTimeZoneAbbreviation: toTimeZone("Z"),
toTimeZoneName: toTimeZone("America/Argentina/Buenos_Aires")
}
1
2
3
4
5
{
toTimeZoneOffset: |-03:00|,
toTimeZoneAbbreviation: |Z|,
toTimeZoneName: |America/Argentina/Buenos_Aires|
}
16.1.20. toUri
toUri(str: String): Uri
Transforms a String
value into a Uri
value.
Parameters
Name | Description |
---|---|
str |
The |
Example
This example shows how toUri
behaves.
1
2
3
4
5
6
7
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
toUriExample: toUri("https://www.google.com/")
}
1
2
3
{
"toUriExample": "https://www.google.com/"
}
16.2. Types
16.2.1. Formatter
Type used for formatting Dates
types and Number
.
Supports the following fields:
-
format
: (optional) The ISO-8601 formatting to use on the date or time. For example, this parameter accepts character patterns patterns based on the Java 8java.time.format
. Anull
value has no effect on the value. -
locale
: (optional) ISO 3166 country code to use, such asUS
,AR
, orES
. Anull
or absent value uses your JVM default. When you pass a translatable format, such aseeee
andMMMM
, alocale
(such as"ES
) transforms the corresponding numeric values to a localized string
1
{ format?: String, locale?: String }
16.2.2. MillisOrSecs
Type used for setting units to "milliseconds"
or "seconds"
.
1
"milliseconds" | "seconds"
16.2.3. PeriodUnits
Type used for setting units of a Period
value to "hours"
, "minutes"
, "seconds"
,
"milliseconds"
, or "nanos"
.
1
"hours" | "minutes" | "seconds" | "milliseconds" | "nanos"
16.2.4. RoundingMode
Type used when rounding decimal values up or down.
1
"UP" | "DOWN" | "CEILING" | "FLOOR" | "HALF_UP" | "HALF_DOWN" | "HALF_EVEN"
17. dw::util::Diff
This utility module calculates the difference between two values and returns a list of differences.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::util::Diff
to the header of your
DataWeave script.
17.1. Functions
17.1.1. diff
diff(actual: Any, expected: Any, diffConfig: { unordered?: Boolean } = {}, path: String = "(root)"): 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 |
---|---|
actual |
The actual value. Can be any data type. |
expected |
The expected value to compare to the actual. Can be any data type. |
diffConfig |
Setting for changing the default to unordered using `{ "unordered" : true} (explained in the introduction). |
Example
This example shows a variety of uses of diff
.
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: []
}
}
17.2. Types
17.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> }
17.2.2. Difference
Describes a single difference between two values at a given structure.
1
{ expected: String, actual: String, path: String }
18. dw::util::Math
A utility module that provides mathematical functions.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::util::Math
to the header of your
DataWeave script.
18.1. Functions
18.1.1. acos
acos(angle: Number): Number | NaN
Returns an arc cosine value that can range from 0.0
through pi.
If the absolute value of the input is greater than 1
,
the result is null
.
Parameters
Name | Description |
---|---|
angle |
Number to convert into it arc cosine value. |
Example
This example shows how acos
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::util::Math
output application/json
---
{
"acos0": acos(0),
"acos13": acos(0.13),
"acos-1": acos(-1),
"acos1": acos(1),
"acos1.1": acos(1.1)
}
1
2
3
4
5
6
7
{
"acos0": 1.5707963267948966,
"acos13": 1.440427347091751,
"acos-1": 3.141592653589793,
"acos1": 0.0,
"acos1.1": null
}
18.1.2. asin
asin(angle: Number): Number | NaN
Returns an arc sine value that can range from -pi/2
through pi/2
.
If the absolute value of the input is greater than 1, the result
is null
.
Parameters
Name | Description |
---|---|
angle |
Number to convert into its arc sine value. |
Example
This example shows how asin
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
%dw 2.0
import * from dw::util::Math
output application/json
---
{
"asin0": asin(0),
"asin13": asin(0.13),
"asin-1": asin(-1),
"asin1.1": asin(1.1)
}
1
2
3
4
5
6
{
"asin0": 0.0,
"asin13": 0.1303689797031455,
"asin-1": -1.5707963267948966,
"asin1.1": null
}
18.1.3. atan
atan(angle: Number): Number
Returns an arc tangent value that can range from -pi/2
through pi/2
.
Parameters
Name | Description |
---|---|
angle |
Number to convert into its arc tangent value. |
Example
This example shows how atan
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Math
output application/json
---
{
"atan0": atan(0),
"atan13": atan(0.13),
"atan-1": atan(-1)
}
1
2
3
4
5
{
"atan0": 0.0,
"atan13": 0.12927500404814307,
"atan-1": -0.7853981633974483
}
18.1.4. cos
cos(angle: Number): Number
Returns the trigonometric cosine of an angle from a given number of radians.
Parameters
Name | Description |
---|---|
angle |
Number of radians in an angle. |
Example
This example shows how cos
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Math
output application/json
---
{
"cos0": cos(0),
"cos13": cos(0.13),
"cos-1": cos(-1)
}
1
2
3
4
5
{
"cos0": 1.0,
"cos13": 0.9915618937147881,
"cos-1": 0.5403023058681398
}
18.1.5. log10
log10(a: Number): Number | NaN
Returns the logarithm base 10 of a number.
Parameters
Name | Description |
---|---|
a |
A |
Example
This example shows how log10
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Math
output application/json
---
{
"log1010": log10(10),
"log1013": log10(0.13),
"log10-20": log10(-20)
}
1
2
3
4
5
{
"log1010": 1.0,
"log1013": -0.8860566476931632,
"log10-20": null
}
18.1.6. logn
logn(a: Number): Number | NaN
Returns the natural logarithm (base e
) of a number.
If the input value is less than or equal to zero,
the result is NaN
(or null
).
Parameters
Name | Description |
---|---|
a |
Number to convert into its natural logarithm. |
Example
This example shows how logn
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Math
output application/json
---
{
"logn10": logn(10),
"logn13": logn(0.13),
"logn-20": logn(-20)
}
1
2
3
4
5
{
"logn10": 2.302585092994046,
"logn13": -2.0402208285265546,
"logn-20": null
}
18.1.7. sin
sin(angle: Number): Number
Returns the trigonometric sine of an angle from a given number of radians.
Parameters
Name | Description |
---|---|
angle |
Number of radians in an angle. |
Example
This example shows how sin
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Math
output application/json
---
{
"sin0": sin(0),
"sin13": sin(0.13),
"sin-1": sin(-1)
}
1
2
3
4
5
{
"sin0": 0.0,
"sin13": 0.12963414261969486,
"sin-1": -0.8414709848078965
}
18.1.8. tan
tan(angle: Number): Number
Returns the trigonometric tangent of an angle from a given number of radians.
Parameters
Name | Description |
---|---|
angle |
Number of radians in an angle. |
Example
This example shows how tan
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Math
output application/json
---
{
"tan0": tan(0),
"tan13": tan(0.13),
"tan-1": tan(-1)
}
1
2
3
4
5
{
"tan0": 0.0,
"tan13": 0.13073731800446006,
"tan-1": -1.5574077246549023
}
18.1.9. toDegrees
toDegrees(angrad: Number): Number
Converts an angle measured in radians to an approximately equivalent number of degrees.
Parameters
Name | Description |
---|---|
angrad |
Number of radians to convert to degrees. |
Example
This example shows how toDegrees
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Math
output application/json
---
{
"toDegrees0.17": toDegrees(0.174),
"toDegrees0": toDegrees(0),
"toDegrees-20": toDegrees(-0.20)
}
1
2
3
4
5
{
"toDegrees0.17": 9.969465635276323832571267395889251,
"toDegrees0": 0E+19,
"toDegrees-20": -11.45915590261646417536927286883822
}
18.1.10. toRadians
toRadians(angdeg: Number): Number
Converts a given number of degrees in an angle to an approximately equivalent number of radians.
Parameters
Name | Description |
---|---|
angdeg |
Number of degrees to convert into radians. |
Example
This example shows how toRadians
behaves with different inputs.
1
2
3
4
5
6
7
8
9
%dw 2.0
import * from dw::util::Math
output application/json
---
{
"toRadians10": toRadians(10),
"toRadians013": toRadians(0.13),
"toRadians-20": toRadians(-20)
}
1
2
3
4
5
{
"toRadians10": 0.1745329251994329576922222222222222,
"toRadians013": 0.002268928027592628449998888888888889,
"toRadians-20": -0.3490658503988659153844444444444444
}
18.2. Variables
18.2.1. E
Variable E
sets the value of mathematical constant e
,
the base of natural logarithms.
18.2.2. PI
Variable PI
sets the value of constant value pi, the ratio
of the circumference of a circle to its diameter.
19. dw::util::Timer
This utility module contains functions for measuring time.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::util::Timer
to the header of your
DataWeave script.
19.1. Functions
19.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 }
19.1.2. duration
duration<T>(valueToMeasure: () -> T): DurationMeasurement<T>
Executes the input function and returns an object with execution time in milliseconds and result of that function.
Parameters
Name | Description |
---|---|
valueToMeasure |
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"
}
19.1.3. time
time<T>(valueToMeasure: () -> 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 |
---|---|
valueToMeasure |
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"
}
]
}
19.1.4. toMilliseconds
toMilliseconds(date: DateTime): Number
Returns the representation of a specified date-time in milliseconds.
Parameters
Name | Description |
---|---|
date |
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 }
19.2. Types
19.2.1. DurationMeasurement
A return type that contains the execution time and result of a function call.
1
{ time: Number, result: T }
19.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 }
20. dw::util::Tree
This utility module provides functions for handling values as tree-data structures.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::util::Tree
to the header of your
DataWeave script.
20.1. Functions
20.1.1. asExpressionString
asExpressionString(path: Path): String
Transforms a Path
value into a string representation of the path.
Parameters
Name | Description |
---|---|
path |
The |
Example
This example transforms a Path
value into a String
representation
of a selector for an attribute of an object.
1
2
3
4
5
6
7
8
%dw 2.0
import * from dw::util::Tree
output application/json
---
asExpressionString([
{kind: OBJECT_TYPE, selector: "user", namespace: null},
{kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}
])
1
".user.@name"
20.1.2. filterArrayLeafs
filterArrayLeafs(value: Any, criteria: (value: Any, path: Path) -> Boolean): Any
Applies a filtering expression to leaf or Path
values of an array.
The leaf values in the array must be SimpleType
or Null
values. See
Core Types
for descriptions of the types.
Parameters
Name | Description |
---|---|
value |
An input value of |
criteria |
Boolean expression to apply to |
Example
This example shows how filterArrayLeafs
behaves with different
inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
%dw 2.0
import * from dw::util::Tree
var myArray = [1, {name: ["", true], test: 213}, "123", null]
output application/json
---
{
a: myArray filterArrayLeafs ((value, path) ->
!(value is Null or value is String)),
b: myArray filterArrayLeafs ((value, path) ->
(value is Null or value == 1)),
c: { a : [1,2] } filterArrayLeafs ((value, path) ->
(value is Null or value == 1)),
d: myArray filterArrayLeafs ((value, path) ->
!isArrayType(path))
}
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
{
"a": [
1,
{
"name": [
true
],
"test": 213
}
],
"b": [
1,
{
"name": [
],
"test": 213
},
null
],
"c": {
"a": [
1
]
},
"d": [
{
"name": [
],
"test": 213
}
]
}
20.1.3. filterObjectLeafs
filterObjectLeafs(value: Any, criteria: (value: Any, path: Path) -> Boolean): Any
Applies a filtering expression to leaf or Path
values of keys in
an object.
The leaf values in the object must be SimpleType
or Null
values. See
Core Types
for descriptions of the types.
Parameters
Name | Description |
---|---|
value |
An input value of |
criteria |
Boolean expression to apply to |
Example
This example shows how filterObjectLeafs
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
%dw 2.0
import * from dw::util::Tree
var myArray = [{name @(mail: "me@me.com", test:123 ): "", id:"test"},
{name: "Me", id:null}]
output application/json
---
{
a: {
name: "Mariano",
lastName: null,
age: 123,
friends: myArray
} filterObjectLeafs ((value, path) ->
!(value is Null or value is String)),
b: { c : null, d : "hello" } filterObjectLeafs ((value, path) ->
(value is Null and isObjectType(path)))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"a": {
"age": 123,
"friends": [
{
},
{
}
]
},
"b": {
"c": null
}
}
20.1.4. filterTree
filterTree(value: Any, criteria: (value: Any, path: Path) -> Boolean): Any
Filters the value or path of nodes in an input based on a
specified criteria
.
The function iterates through the nodes in the input. The
criteria
can apply to the value or path in the input. If
the criteria
evaluates to true
, the node remains in the
output. If false
, the function filters out the node.
Parameters
Name | Description |
---|---|
value |
The value to filter. |
criteria |
The expression that determines whether to filter the node. |
Example
This example shows how filterTree
behaves with different inputs.
The output is application/dw
for demonstration purposes.
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
%dw 2.0
import * from dw::util::Tree
output application/dw
---
{
a: {
name : "",
lastName @(foo: ""): "Achaval",
friends @(id: 123): [{id: "", test: true}, {age: 123}, ""]
} filterTree ((value, path) ->
value match {
case s is String -> !isEmpty(s)
else -> true
}
),
b: null filterTree ((value, path) -> value is String),
c: [
{name: "Mariano", friends: []},
{test: [1,2,3]},
{dw: ""}
] filterTree ((value, path) ->
value match {
case a is Array -> !isEmpty(a as Array)
else -> true
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
a: {
lastName: "Achaval",
friends @(id: 123): [
{
test: true
},
{
age: 123
}
]
},
b: null,
c: [
{
name: "Mariano"
},
{
test: [
1,
2,
3
]
},
{
dw: ""
}
]
}
20.1.5. isArrayType
isArrayType(path: Path): Boolean
Returns true
if the provided Path
value is an ARRAY_TYPE
expression.
Parameters
Name | Description |
---|---|
path |
The |
Example
This example shows how isArrayType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::util::Tree
output application/json
---
{
a: isArrayType([{kind: OBJECT_TYPE, selector: "user", namespace: null},
{kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}]),
b: isArrayType([{kind: OBJECT_TYPE, selector: "user", namespace: null},
{kind: ARRAY_TYPE, selector: 0, namespace: null}]),
c: isArrayType([{kind: ARRAY_TYPE, selector: 0, namespace: null}])
}
1
2
3
4
5
{
"a": false,
"b": true,
"c": true
}
20.1.6. isAttributeType
isAttributeType(path: Path): Boolean
Returns true
if the provided Path
value is an ATTRIBUTE_TYPE
expression.
Parameters
Name | Description |
---|---|
path |
The |
Example
This example shows how isAttributeType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::util::Tree
output application/json
---
{
a: isAttributeType([{kind: OBJECT_TYPE, selector: "user", namespace: null},
{kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}]),
b: isAttributeType([{kind: OBJECT_TYPE, selector: "user", namespace: null},
{kind: ARRAY_TYPE, selector: "name", namespace: null}]),
c: isAttributeType([{kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}])
}
1
2
3
4
5
{
"a": true,
"b": false,
"c": true
}
20.1.7. isObjectType
isObjectType(path: Path): Boolean
Returns true
if the provided Path
value is an OBJECT_TYPE
expression.
Parameters
Name | Description |
---|---|
path |
The |
Example
This example shows how isObjectType
behaves with different inputs.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::util::Tree
output application/json
---
{
a: isObjectType([{kind: OBJECT_TYPE, selector: "user", namespace: null},
{kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}]),
b: isObjectType([{kind: OBJECT_TYPE, selector: "user", namespace: null},
{kind: OBJECT_TYPE, selector: "name", namespace: null}]),
c: isObjectType([{kind: OBJECT_TYPE, selector: "user", namespace: null}])
}
1
2
3
4
5
{
"a": false,
"b": true,
"c": true
}
20.1.8. mapLeafValues
mapLeafValues(value: Any, callback: (value: Any, path: Path) -> Any): Any
Maps the terminal (leaf) nodes in the tree.
Leafs nodes cannot have an object or an array as a value.
Parameters
Name | Description |
---|---|
value |
The value to map. |
callback |
The mapper function. |
Example
This example transforms all the string values to upper case.
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
import * from dw::util::Tree
output application/json
---
{
user: [{
name: "mariano",
lastName: "achaval"
}],
group: "data-weave"
} mapLeafValues (value, path) -> upper(value)
1
2
3
4
5
6
7
8
9
{
"user": [
{
"name": "MARIANO",
"lastName": "ACHAVAL"
}
],
"group": "DATA-WEAVE"
}
Example
This example returns a new value for an object, array, or attribute.
1
2
3
4
5
6
7
8
9
10
11
12
%dw 2.0
output application/json
import * from dw::util::Tree
---
{
name: "Mariano",
test: [1,2,3]
} mapLeafValues ((value, path) -> if(isObjectType(path))
"***"
else if(isArrayType(path))
"In an array"
else "Is an attribute")
1
2
3
4
5
6
7
8
{
"name": "***",
"test": [
"In an array",
"In an array",
"In an array"
]
}
20.1.9. nodeExists
nodeExists(value: Any, callback: (value: Any, path: Path) -> Boolean): Boolean
Returns true
if any node in a given tree validates against
the specified criteria.
Parameters
Name | Description |
---|---|
value |
The value to search. |
callback |
The criteria to apply to the input |
Example
This example checks for each user by name and last name. Notice
that you can also reference a value
with $
and the path
with $$
.
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
%dw 2.0
import * from dw::util::Tree
var myObject = {
user: [{
name: "mariano",
lastName: "achaval",
friends: [
{
name: "julian"
},
{
name: "tom"
}
]
},
{
name: "leandro",
lastName: "shokida",
friends: [
{
name: "peter"
},
{
name: "robert"
}
]
}
]
}
output application/json
---
{
mariano : myObject nodeExists ((value, path) -> path[-1].selector == "name" and value == "mariano"),
julian : myObject nodeExists ((value, path) -> path[-1].selector == "name" and value == "julian"),
tom : myObject nodeExists ($$[-1].selector == "name" and $ == "tom"),
leandro : myObject nodeExists ($$[-1].selector == "name" and $ == "leandro"),
peter : myObject nodeExists ($$[-1].selector == "name" and $ == "peter"),
wrongField: myObject nodeExists ($$[-1].selector == "wrongField"),
teo: myObject nodeExists ($$[-1].selector == "name" and $ == "teo")
}
1
2
3
4
5
6
7
8
9
{
"mariano": true,
"julian": true,
"tom": true,
"leandro": true,
"peter": true,
"wrongField": false,
"teo": false
}
20.2. Variables
20.2.1. ARRAY_TYPE
Variable used to identify a PathElement
value as an array.
20.2.2. ATTRIBUTE_TYPE
Variable used to identify a PathElement
value as an attribute.
20.2.3. OBJECT_TYPE
Variable used to identify a PathElement
value as an object.
20.3. Types
20.3.1. Path
Type that consists of an array of PathElement
values that
identify the location of a node in a tree. An example is
[{kind: OBJECT_TYPE, selector: "user", namespace: null}, {kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}] as Path
.
1
Array<PathElement>
20.3.2. PathElement
Type that represents a selection of a node in a path.
An example is {kind: ARRAY_TYPE, selector: "name", namespace: null} as PathElement
.
1
{| kind: "Object" | "Attribute" | "Array", selector: String | Number, namespace: Namespace | Null |}
21. dw::util::Values
This utility module simplifies changes to values.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::util::Values
to the header of your
DataWeave script.
21.1. Functions
21.1.1. attr
attr(namespace: Namespace | Null = null, name: String): PathElement
This function creates a PathElement
to use for selecting an XML
attribute and populates the type’s selector
field with the given string.
Some versions of the update
and mask
functions accept a PathElement
as
an argument.
Parameters
Name | Description |
---|---|
namespace |
The namespace of the attribute to select. If not specified, a null value is set. |
name |
The string that names the attribute to select. |
Example
This example creates an attribute selector for a specified namespace
(ns0
) and sets the selector’s value to "myAttr"
. In the
output, also note that the value of the "kind"
key is "Attribute"
.
1
2
3
4
5
6
%dw 2.0
output application/json
import * from dw::util::Values
ns ns0 http://acme.com/fo
---
attr(ns0 , "myAttr")
1
2
3
4
5
{
"kind": "Attribute",
"namespace": "http://acme.com/foo",
"selector": "myAttr"
}
21.1.2. field
field(namespace: Namespace | Null = null, name: String): PathElement
This function creates a PathElement
data type to use for selecting an
object field and populates the type’s selector
field with the given
string.
Some versions of the update
and mask
functions accept a PathElement
as
an argument.
Parameters
Name | Description |
---|---|
namespace |
The namespace of the field to select. If not specified, a null value is set. |
name |
A string that names the attribute to select. |
Example
This example creates an object field selector for a specified namespace
(ns0
) and sets the selector’s value to "myFieldName"
. In the
output, also note that the value of the "kind"
key is "Object"
.
1
2
3
4
5
6
%dw 2.0
output application/json
import * from dw::util::Values
ns ns0 http://acme.com/foo
---
field(ns0 , "myFieldName")
1
2
3
4
5
{
"kind": "Object",
"namespace": "http://acme.com/foo",
"selector": "myFieldName"
}
21.1.3. index
index(index: Number): PathElement
This function creates a PathElement
data type to use for selecting an
array element and populates the type’s selector
field with the specified
index.
Some versions of the update
and mask
functions accept a PathElement
as
an argument.
Parameters
Name | Description |
---|---|
index |
The index. |
Example
This example creates an selector for a specified index.
It sets the selector’s value to 0
. In the
output, also note that the value of the "kind"
key is "Array"
.
1
2
3
4
5
6
%dw 2.0
output application/json
import * from dw::util::Values
ns ns0 http://acme.com/foo
---
index(0)
1
2
3
4
5
{
"kind": "Array",
"namespace": null,
"selector": 0
}
21.1.4. mask
mask(value: Null, fieldName: String | Number | PathElement): (newValueProvider: (oldValue: Any, path: Path) -> Any) -> Null
Helper function that enables mask
to work with a null
value.
mask(value: Any, selector: PathElement): (newValueProvider: (oldValue: Any, path: Path) -> Any) -> Any
This mask
function replaces all simple elements that match the specified
criteria.
Simple elements do not have child elements and cannot be objects or arrays.
Parameters
Name | Description |
---|---|
value |
A value to use for masking. The value can be any DataWeave type. |
selector |
The |
Example
This example shows how to mask the value of a password
field in
an array of objects. It uses field("password")
to return the PathElement
that it passes to mask
. It uses with ""
to specify the value
() to use for masking.
1
2
3
4
5
%dw 2.0
output application/json
import * from dw::util::Values
---
[{name: "Peter Parker", password: "spiderman"}, {name: "Bruce Wayne", password: "batman"}] mask field("password") with "*****"
1
2
3
4
5
6
7
8
9
10
[
{
"name": "Peter Parker",
"password": "*****"
},
{
"name": "Bruce Wayne",
"password": "*****"
}
]
mask(value: Any, fieldName: String): (newValueProvider: (oldValue: Any, path: Path) -> Any) -> Any
This mask
function selects a field by its name.
Parameters
Name | Description |
---|---|
value |
The value to use for masking. The value can be any DataWeave type. |
fieldName |
A string that specifies the name of the field to mask. |
Example
This example shows how to perform masking using the name of a field in the input. It modifies the values of all fields with that value.
1
2
3
4
5
%dw 2.0
output application/json
import * from dw::util::Values
---
[{name: "Peter Parker", password: "spiderman"}, {name: "Bruce Wayne", password: "batman"}] mask "password" with "*****"
1
2
3
4
5
6
7
8
9
10
[
{
"name": "Peter Parker",
"password": "*****"
},
{
"name": "Bruce Wayne",
"password": "*****"
}
]
mask(value: Any, i: Number): (newValueProvider: (oldValue: Any, path: Path) -> Any) -> Any
This mask
function selects an element from array by its index.
Parameters
Name | Description |
---|---|
value |
The value to mask. The value can be any DataWeave type. |
index |
The index to mask. The index must be a number. |
Example
This example shows how mask
acts on all elements in the nested arrays.
It changes the value of each element at index 1
to false
.
1
2
3
4
5
%dw 2.0
output application/json
import * from dw::util::Values
---
[[123, true], [456, true]] mask 1 with false
1
2
3
4
5
6
7
8
9
10
[
[
123,
false
],
[
456,
false
]
]
21.1.5. update
update(objectValue: Object, fieldName: String): UpdaterValueProvider<Object>
This update
function updates a field in an object with the specified
string value.
The function returns a new object with the specified field and value.
Parameters
Name | Description |
---|---|
objectValue |
The object to update. |
fieldName |
A string that provides the name of the field. |
Example
This example updates the name
field in the object {name: "Mariano"}
with
the specified value.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
{name: "Mariano"} update "name" with "Data Weave"
1
2
3
{
"name": "Data Weave"
}
update(objectValue: Object, fieldName: PathElement): UpdaterValueProvider<Object>
This update
function updates an object field with the specified
PathElement
value.
The function returns a new object with the specified field and value.
Parameters
Name | Description |
---|---|
objectValue |
The object to update. |
fieldName |
A |
Example
This example updates the value of a name
field in the object
{name: "Mariano"}
. It uses field("name")
to return the PathElement
that it passes to update
. It uses with "Data Weave"
to specify the value
(Data Weave
) of name
.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
{name: "Mariano"} update field("name") with "Data Weave"
1
2
3
{
"name": "Data Weave"
}
update(arrayValue: Array, indexToUpdate: Number): UpdaterValueProvider<Array>
Updates an array index with the specified value.
This update
function returns a new array that changes the value of
the specified index.
Parameters
Name | Description |
---|---|
objectValue |
The array to update. |
indexToUpdate |
The index of the array to update. The index must be a number. |
Example
This example replaces the value 2
(the index is 1
) with 5
in the
the input array [1,2,3]
.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
[1,2,3] update 1 with 5
1
2
3
4
5
[
1,
5,
3
]
update(arrayValue: Array, indexToUpdate: String): UpdaterValueProvider<Array>
This update
function updates all objects within the specified array with
the given string value.
Parameters
Name | Description |
---|---|
objectValue |
The array of objects to update. |
indexToUpdate |
A string providing the name of the field to update. |
Example
This example updates value of the role
fields in the array of objects.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
[{role: "a", name: "spiderman"}, {role: "b", name: "batman"}] update "role" with "Super Hero"
1
2
3
4
5
6
7
8
[{
"role": "Super Hero",
"name": "spiderman"
},
{
"role": "Super Hero",
"name": "batman"
}]
update(arrayValue: Array, indexToUpdate: PathElement): UpdaterValueProvider<Array>
This update
function updates the specified index of an array with the
given PathElement
value.
The function returns a new array that contains given value at the specified index.
Parameters
Name | Description |
---|---|
objectValue |
The array to update. |
indexToUpdate |
The index of the array to update. The index must be specified as a |
Example
This example updates the value of an element in the input array. Notice
that it uses index(1)
to return the index as a PathElement
, which
it passes to update
. It replaces the value 2
at that index with 5
.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
[1,2,3] update index(1) with 5
1
2
3
4
5
[
1,
5,
3
]
update(value: Array | Object | Null, path: Array<String | Number | PathElement>): UpdaterValueProvider<Array | Object | Null>
Updates the value at the specified path with the given value.
Parameters
Name | Description |
---|---|
objectValue |
The value to update. Accepts an array, object, or null value. |
path |
The path to update. The path must be an array of strings, numbers, or `PathElement`s. |
Example
This example updates the name of the user.
1
2
3
4
5
%dw 2.0
import * from dw::util::Values
output application/json
---
{user: {name: "Mariano"}} update ["user", field("name")] with "Data Weave"
1
2
3
4
5
{
"user": {
"name": "Data Weave"
}
}
update(value: Null, toUpdate: Number | String | PathElement): UpdaterValueProvider<Null>
Helper function that enables update
to work with a null
value.
21.2. Types
21.2.1. UpdaterValueProvider
Type that represents the output type of the update function.
1
(newValueProvider: (oldValue: Any, index: Number) -> Any) -> ReturnType
22. dw::xml::Dtd
This module contains helper functions for working with XML doctype declarations.
To use this module, you must import it to your DataWeave code, for example,
by adding the line import * from dw::xml::Dtd
to the header of your
DataWeave script.
22.1. Functions
22.1.1. docTypeAsString
docTypeAsString(docType: DocType): String
Transforms a DocType
value to a string representation.
Parameters
Name | Type | Description |
---|---|---|
docType |
DocType |
The |
Example
This example transforms a DocType
value that includes a systemId
to a string representation.
1
2
3
4
5
%dw 2.0
import * from dw::xml::Dtd
output application/json
---
docTypeAsString({rootName: "cXML", systemId: "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd"})
1
"cXML SYSTEM http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd"
Example
This example transforms a DocType
value that includes a publicId
and systemId
to a string representation.
1
2
3
4
5
%dw 2.0
import * from dw::xml::Dtd
output application/json
---
docTypeAsString({rootName: "html", publicId: "-//W3C//DTD XHTML 1.0 Transitional//EN", systemId: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"})
1
"html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
22.2. Types
22.2.1. DocType
DataWeave type for representing a doctype declaration that is part of an XML file. Supports the following fields:
-
rootName
: Root element of the declaration. -
publicId
: Publicly available standard (optional). -
systemId
: Local URL (optional). -
internalSubset
: Internal DTD subset (optional).
1
{ rootName: String, publicId?: String, systemId?: String, internalSubset?: String }