### TimeFactory Example in DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Provides an example of creating a TimeFactory in DataWeave, which merges LocalTimeFactory and Zoned types. It demonstrates setting hour, minutes, seconds, and timezone. ```DataWeave %dw 2.0 output application/json --- {hour: 8, minutes: 31, seconds: 55, timeZone : |-03:00|} as TimeFactory ``` -------------------------------- ### LocalTimeFactory Example in DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Shows an example of a LocalTimeFactory in DataWeave, which includes hour, minutes, and seconds. The example demonstrates that these fields accept any Number value. ```DataWeave %dw 2.0 output application/json --- {hour: 8, minutes: 31, seconds: 55} ``` -------------------------------- ### DataWeave Reduce Examples Source: https://dataweave.mulesoft.com/learn/docs.html This section provides examples of the DataWeave reduce function applied to arrays of numbers, strings, objects, and booleans, demonstrating different reduction strategies and initial accumulator values. ```APIDOC ## DataWeave Reduce Function Examples ### Description Demonstrates various applications of the `reduce` function in DataWeave for transforming arrays and strings. ### Examples **1. Summing numeric values in an array:** ```dataweave %dw 2.0 output application/json --- [2, 3] reduce ($ + $$) ``` **Output:** `5` **2. Sum, Concatenation, and Empty List Handling:** ```dataweave %dw 2.0 var myNums = [1,2,3,4] var myEmptyList = [] output application/json --- { "sum" : myNums reduce ($$ + $), "concat" : myNums reduce ($$ ++ $), "emptyList" : myEmptyList reduce ($$ ++ $) } ``` **Output:** `{ "sum": 10, "concat": "1234", "emptyList": null }` **3. String Concatenation, Sum with Initial Accumulator, Multiplication:** ```dataweave %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) } ``` **Output:** `{ "concat": "zabcd", "sum": 18, "multiply": 18, "multiplyAcc": 36 }` **4. Advanced Reduce Operations on Various Data Types:** ```dataweave %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) } ``` **Output:** `{ "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(@StreamCapable items: Array, callback: (item: T, accumulator: A) -> A): A Applies a reduction expression to the elements of an array. ### 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 #### Array Reduce - **items** (Array) - Required - The array to reduce. - **callback** ((item: T, accumulator: A) -> A) - Required - The function to apply. It takes the current item and the accumulator, and returns the new accumulator value. #### String Reduce - **text** (String) - Required - The string to reduce. - **callback** ((item: String, accumulator: String) -> String) - Required - The function to apply. It takes the current character and the accumulator, and returns the new accumulator value. ### Response #### Success Response (200) - **(A | String)** - The final accumulated value after applying the reduction to all elements. ``` -------------------------------- ### LocalDateTimeFactory Example in DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Illustrates the construction of a LocalDateTimeFactory in DataWeave, combining DateFactory and LocalTimeFactory. The example shows setting date and time components, noting that the timeZone field is optional. ```DataWeave %dw 2.0 output application/json --- {day: 21, month: 1, year: 2021, hour: 8, minutes: 31, seconds: 55, timeZone : |-03:00|} as LocalDateTimeFactory ``` -------------------------------- ### readLinesWith Example Source: https://dataweave.mulesoft.com/learn/docs.html Splits binary content into lines based on a specified charset. ```APIDOC ## POST /example/readLinesWith ### Description Splits binary content into lines and returns them as an array of strings. ### Method POST ### Endpoint /example/readLinesWith ### Parameters #### Request Body - **content** (Binary) - Required - The binary data to read and split. - **charset** (String) - Required - The encoding to use for reading the content. ### Request Example ```json { "content": "data:application/octet-stream;base64,TGluZSAxXG5MaW5lIDJcbkxpbmUgM1xuTGl ``` -------------------------------- ### Zip Arrays - Basic Example Source: https://dataweave.mulesoft.com/learn/docs.html This example illustrates the basic functionality of the `zip` function, which merges elements from two arrays into an array of arrays. It pairs elements based on their index. ```DataWeave %dw 2.0 output application/json --- [0,1] zip ["a","b"] ``` -------------------------------- ### DataWeave keySet Function Example Source: https://dataweave.mulesoft.com/learn/docs.html Illustrates the keySet function from dw::core::Objects, which returns an array of keys from an object. The example shows its behavior with simple objects and contrasts it with nameSet when dealing with XML input containing attributes and namespaces. ```DataWeave %dw 2.0 import * from dw::core::Objects output application/json --- { "keySet" : keySet({ "a" : true, "b" : 1}) } ``` ```DataWeave %dw 2.0 import * from dw::core::Objects var myVar = read(' ', '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 $.@]) } ``` -------------------------------- ### fromHex Example Source: https://dataweave.mulesoft.com/learn/docs.html Transforms a hexadecimal string to binary data, outputting in application/dw format. ```APIDOC ## POST /example/fromHex ### Description Transforms a hexadecimal string to binary data. ### Method POST ### Endpoint /example/fromHex ### Parameters #### Request Body - **hexString** (String) - Required - The hexadecimal string to convert. ### Request Example ```json { "hexString": "4D756C65" } ``` ### Response #### Success Response (200) - **hexToBinary** (Binary) - The converted binary data. #### Response Example ```json { "hexToBinary": "TXVsZQ==" } ``` ``` -------------------------------- ### toHex Example Source: https://dataweave.mulesoft.com/learn/docs.html Transforms binary data into a hexadecimal string. ```APIDOC ## POST /example/toHex ### Description Transforms a binary value into a hexadecimal string. ### Method POST ### Endpoint /example/toHex ### Parameters #### Request Body - **content** (Binary) - Required - The binary value to transform. ### Request Example ```json { "content": "TXVsZQ==" } ``` ### Response #### Success Response (200) - **hexString** (String) - The hexadecimal representation of the binary data. #### Response Example ```json { "hexString": "4D756C65" } ``` ``` -------------------------------- ### DataWeave nameSet Function Example Source: https://dataweave.mulesoft.com/learn/docs.html Shows the nameSet function from dw::core::Objects, which returns an array of keys from an object. This example provides a basic usage and is also used in comparison with keySet to illustrate differences in handling XML namespaces and attributes. ```DataWeave %dw 2.0 import * from dw::core::Objects output application/json --- { "nameSet" : nameSet({ "a" : true, "b" : 1}) } ``` -------------------------------- ### toBase64 Example Source: https://dataweave.mulesoft.com/learn/docs.html Transforms binary data into a Base64 encoded string. ```APIDOC ## POST /example/toBase64 ### Description Transforms a binary value into a Base64 encoded string. ### Method POST ### Endpoint /example/toBase64 ### Parameters #### Request Body - **content** (Binary) - Required - The binary value to transform. ### Request Example ```json { "content": "...binary data..." } ``` ### Response #### Success Response (200) - **base64String** (String) - The Base64 encoded string. #### Response Example ```json { "base64String": "/9j/4AAQSkZJRgABAQEAYABgAAD//..." } ``` ``` -------------------------------- ### Zoned Type Example in DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Illustrates the Zoned type in DataWeave, which contains a timezone key. The example shows how to specify a TimeZone value. ```DataWeave %dw 2.0 output application/json --- { timezone : |-03:00|} ``` -------------------------------- ### Get Key-Value Pairs and Attributes with entrySet in DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Utilizes the `entrySet` function from `dw::core::Objects` to extract key, value, and attribute information from an XML input. The example parses an XML string and then applies `entrySet` to its root element. ```DataWeave %dw 2.0 import * from dw::core::Objects var myVar = read('true1', 'application/xml') output application/json --- { "entrySet" : entrySet(myVar) } ``` -------------------------------- ### atBeginningOfDay Source: https://dataweave.mulesoft.com/learn/docs.html Returns a new date/time value with the time component set to the start of the day (00:00:00). ```APIDOC ## FUNCTION atBeginningOfDay ### Description Returns a new value that changes the time component of the input to the beginning of the specified day (00:00:00). ### Parameters - **localDateTime/dateTime** (DateTime/LocalDateTime) - Required - The date/time value to reference. ### Request Example %dw 2.0 import * from dw::core::Dates --- { "atBeginningOfDayDateTime": atBeginningOfDay(|2020-10-06T18:23:20.351-03:00|) } ### Response #### Success Response (200) - **result** (String) - The normalized date string at 00:00:00. #### Response Example { "atBeginningOfDayDateTime": "2020-10-06T00:00:00-03:00" } ``` -------------------------------- ### DateTimeFactory Example in DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates the creation of a DateTimeFactory value in DataWeave, which combines DateFactory, LocalTimeFactory, and Zoned types. It shows how to specify day, month, year, hour, minutes, seconds, and timezone. ```DataWeave %dw 2.0 output application/json --- {day: 21, month: 1, year: 2021, hour: 8, minutes: 31, seconds: 55, timeZone : |-03:00|} as DateTimeFactory ``` -------------------------------- ### writeLinesWith Example Source: https://dataweave.mulesoft.com/learn/docs.html Writes an array of strings as binary content, adding newlines between elements. ```APIDOC ## POST /example/writeLinesWith ### Description Writes an array of strings as binary content, inserting newlines between each string. ### Method POST ### Endpoint /example/writeLinesWith ### Parameters #### Request Body - **lines** (Array) - Required - An array of strings to write. - **charset** (String) - Required - The encoding to use when writing the content. ### Request Example ```json { "lines": ["Line 1", "Line 2", "Line 3"], "charset": "UTF-8" } ``` ### Response #### Success Response (200) - **binaryContent** (Binary) - The resulting binary content with lines separated by newlines. #### Response Example ```json { "binaryContent": "Line 1\nLine 2\nLine 3\n" } ``` ``` -------------------------------- ### dw::util::Tree - nodeExists Example Source: https://dataweave.mulesoft.com/learn/docs.html This example demonstrates how to use the `nodeExists` function from the `dw::util::Tree` module to check for the existence of nodes within a JSON object based on their path and value. ```APIDOC ## POST /example/tree/nodeExists ### Description This endpoint demonstrates the usage of the `nodeExists` function from the `dw::util::Tree` module. It checks for the existence of specific nodes within a JSON structure based on provided criteria, utilizing path and value references. ### Method POST ### Endpoint /example/tree/nodeExists ### Parameters #### Query Parameters - **none** #### Request Body - **myObject** (Object) - The input JSON object to query. ### Request Example ```json { "myObject": { "user": [ { "name": "mariano", "lastName": "achaval", "friends": [ { "name": "julian" }, { "name": "tom" } ] }, { "name": "leandro", "lastName": "shokida", "friends": [ { "name": "peter" }, { "name": "robert" } ] } ] } } ``` ### Response #### Success Response (200) - **mariano** (Boolean) - Indicates if a node with name 'mariano' exists. - **julian** (Boolean) - Indicates if a node with name 'julian' exists. - **tom** (Boolean) - Indicates if a node with name 'tom' exists. - **leandro** (Boolean) - Indicates if a node with name 'leandro' exists. - **peter** (Boolean) - Indicates if a node with name 'peter' exists. - **wrongField** (Boolean) - Indicates if a node with 'wrongField' exists. - **teo** (Boolean) - Indicates if a node with name 'teo' exists. #### Response Example ```json { "mariano": true, "julian": true, "tom": true, "leandro": true, "peter": true, "wrongField": false, "teo": false } ``` ``` -------------------------------- ### dw::util::Coercions - toUri Example Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates the usage of the `toUri` function from the `dw::util::Coercions` module to convert a string to a URI. ```APIDOC ## POST /dw::util::Coercions ### Description Converts a string to a URI. ### Method POST ### Endpoint /dw::util::Coercions ### Parameters #### Request Body - **input** (String) - Required - The string to convert to a URI. ### Request Example ```json { "input": "https://www.google.com/" } ``` ### Response #### Success Response (200) - **toUriExample** (String) - The converted URI string. #### Response Example ```json { "toUriExample": "https://www.google.com/" } ``` ``` -------------------------------- ### GET dw::System::envVars Source: https://dataweave.mulesoft.com/learn/docs.html Retrieves all environment variables defined in the host system. ```APIDOC ## GET dw::System::envVars ### Description Returns all the environment variables defined in the host system as a dictionary. ### Method GET ### Endpoint dw::System::envVars() ### Response #### Success Response (200) - **result** (Dictionary) - A dictionary containing all environment variables. #### Response Example ``` { "SHELL": "/bin/bash", "PATH": "/usr/bin:/bin" } ``` ``` -------------------------------- ### Zip Arrays - Multiple Scenarios Source: https://dataweave.mulesoft.com/learn/docs.html This example showcases the `zip` function's behavior with arrays of different lengths. It demonstrates how `zip` handles cases where one array is shorter or longer than the other, returning only paired elements. ```DataWeave %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"] } ``` -------------------------------- ### Constructing Multipart Form Data with Multipart::field Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates how to create a multipart/form-data output containing multiple parts. The example shows how to define parts with specific MIME types and optional filenames using the Multipart::field function. ```DataWeave %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") } } ``` -------------------------------- ### Read and Transform Data with readUrl Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates how to ingest data from various sources like classpath files or remote URLs. These examples show how to parse JSON, CSV, and DWL formats into different output structures. ```DataWeave %dw 2.0 var myJsonSnippet = readUrl("classpath://myJsonSnippet.json", "application/json") output application/csv --- (myJsonSnippet.results map(item) -> item.profile) ``` ```DataWeave %dw 2.0 output application/json --- readUrl("https://mywebsite.com/data.csv", "application/csv", {"header" : false}) ``` ```DataWeave %dw 2.0 output application/json --- (readUrl("classpath://name.dwl", "application/dw")).firstName ``` -------------------------------- ### Convert String to Time using toTime Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates transforming strings into Time objects using formatters or specific format strings. Includes error handling examples using the try function. ```DataWeave %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 } ``` ```DataWeave %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") } ``` -------------------------------- ### Extract substrings with substringAfter and substringAfterLast in DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates how to extract parts of a string following a specific separator. Includes examples for both first and last occurrences and handles null inputs. ```DataWeave %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", "") } ``` ```DataWeave %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", "") } ``` -------------------------------- ### DataWeave partition Array Example Source: https://dataweave.mulesoft.com/learn/docs.html Shows the partition function in DataWeave, which separates an array into two sub-arrays: one containing elements that satisfy a given condition and another with elements that do not. The Arrays module is required for this function. ```DataWeave %dw 2.0 import * from dw::core::Arrays output application/json var arr = [0,1,2,3,4,5] --- arr partition (item) -> isEven(item) ``` -------------------------------- ### Extract substrings with substringBefore and substringBeforeLast in DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates how to extract parts of a string preceding a specific separator. Includes examples for both first and last occurrences and handles null inputs. ```DataWeave %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", "") } ``` ```DataWeave %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", "") } ``` -------------------------------- ### DataWeave someEntry Function Example Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates the behavior of the `someEntry` function from `dw::core::Objects` with various inputs and conditions. It checks if any entry in an object satisfies a given condition. ```DataWeave %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" } ``` -------------------------------- ### DataWeave everyEntry Function Example Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates the usage of the everyEntry function from dw::core::Objects to check if all entries in an object satisfy a given condition. It handles various input types including empty objects and null values. ```DataWeave %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") } ``` -------------------------------- ### DataWeave leftJoin Array Example Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates the leftJoin function in DataWeave, which returns all objects from the left-side array and joins items from the right-side array based on matching IDs. It requires importing the Arrays module. ```DataWeave %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) ``` -------------------------------- ### DataWeave valueSet Function Example Source: https://dataweave.mulesoft.com/learn/docs.html Shows the usage of the `valueSet` function from `dw::core::Objects`, which extracts all values from an object and returns them as an array. This is useful for processing only the values within an object. ```DataWeave %dw 2.0 import * from dw::core::Objects output application/json --- { "valueSet" : valueSet({a: true, b: 1}) } ``` -------------------------------- ### Reset Time components to the beginning of the hour using DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates the atBeginningOfHour function, which resets the minutes and seconds of DateTime, LocalDateTime, LocalTime, and Time objects to the start of the hour. ```DataWeave %dw 2.0 import * from dw::core::Dates output application/json --- { "atBeginningOfHourDateTime": atBeginningOfHour(|2020-10-06T18:23:20.351-03:00|), "atBeginningOfHourLocalDateTime": atBeginningOfHour(|2020-10-06T18:23:20.351|), "atBeginningOfHourLocalTime": atBeginningOfHour(|18:23:20.351|), "atBeginningOfHourTime": atBeginningOfHour(|18:23:20.351-03:00|) } ``` -------------------------------- ### Create xsi:type Attribute for XML Source: https://dataweave.mulesoft.com/learn/docs.html This example demonstrates the usage of the `xsiType` function to create an `xsi:type` attribute for XML output. It shows how to specify the type name and its associated namespace. ```DataWeave %dw 2.0 output application/xml ns acme http://acme.com --- { user @((xsiType("user", acme))): { name: "Peter", lastName: "Parker" } } ``` -------------------------------- ### DataWeave between Function Example for Periods Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates the `between` function from `dw::core::Periods`, which calculates the duration between two dates. It returns a Period value representing the difference in years, months, and days. The start date is inclusive, and the end date is exclusive. ```DataWeave 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|) } ``` -------------------------------- ### Write String to Plain Text in JSON Source: https://dataweave.mulesoft.com/learn/docs.html This example demonstrates how to use the `write` function to convert a string to plain text and embed it within a JSON object. It specifies the input value and the desired output content type. ```DataWeave %dw 2.0 output application/json --- { hello : write("world", "text/plain") } ``` -------------------------------- ### DataWeave mergeWith Function Example Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates the mergeWith function from dw::core::Objects, which appends key-value pairs from a source object to a target object. It highlights the behavior when keys overlap, where the source value replaces the target value. ```DataWeave %dw 2.0 import mergeWith from dw::core::Objects output application/json --- { "mergeWith" : { "a" : true, "b" : 1} mergeWith { "a" : false, "c" : "Test"} } ``` -------------------------------- ### Group objects using groupBy in DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates how to group elements in an object or array based on specific criteria. The first example uses an anonymous function to transform keys, while the second shows grouping XML data. ```DataWeave %dw 2.0 output application/json --- { "a" : "b", "c" : "d"} groupBy upper($) ``` ```DataWeave %dw 2.0 var myRead = read("9.9910.99","application/xml") output application/json --- myRead.prices groupBy "costs" ``` -------------------------------- ### Retrieve environment variables using dw::System Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates how to import and use the dw::System module to retrieve specific or all environment variables from the host system. ```DataWeave %dw 2.0 import * from dw::System output application/json --- { "envVars" : [ "real" : envVar("SHELL"), "fake" : envVar("FAKE_ENV_VAR") ] } %dw 2.0 import dw::System output application/json --- { "envVars" : dw::System::envVars().SHELL } ``` -------------------------------- ### Convert to URI using Coercions Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates the usage of the `toUri` function from the `dw::util::Coercions` module. This function converts a given string to a URI format. The example shows a simple string input and its corresponding URI output. ```DataWeave %dw 2.0 import * from dw::util::Coercions output application/json --- { toUriExample: toUri("https://www.google.com/") } ``` -------------------------------- ### Comprehensive DataWeave Reduce Examples on Diverse Data Types Source: https://dataweave.mulesoft.com/learn/docs.html Showcases a wide range of 'reduce' function applications in DataWeave, including operations on arrays of numbers, strings, objects, and booleans. It demonstrates various reduction patterns, default accumulator values, and handling of empty arrays. ```DataWeave %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) } ``` -------------------------------- ### GET /math/random Source: https://dataweave.mulesoft.com/learn/docs.html Generates a pseudo-random number between 0.0 and 1.0. ```APIDOC ## GET /math/random ### Description Returns a pseudo-random number greater than or equal to 0.0 and less than 1.0. ### Method GET ### Endpoint /math/random ### Response #### Success Response (200) - **value** (Number) - A random float value. #### Response Example { "value": 0.4829102 } ``` -------------------------------- ### Filter Array Leaf Values with DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html This DataWeave example illustrates the `filterArrayLeafs` function from the `dw::util::Tree` module. It applies a filtering criteria to leaf values within arrays, retaining only those that satisfy the condition. The example shows different filtering scenarios, including filtering out nulls, strings, and non-array types. ```DataWeave %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)) } ``` -------------------------------- ### Advanced Array Reduction with Accumulators in DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Illustrates advanced reduction techniques in DataWeave, including setting initial accumulator values for sum and concatenation, and performing element-wise multiplication within an array. It also shows how to modify the accumulator's initial value for different results. ```DataWeave %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) } ``` -------------------------------- ### Execute DataWeave scripts dynamically using run() Source: https://dataweave.mulesoft.com/learn/docs.html This snippet demonstrates how to use the dw::Runtime::run function to execute scripts. It includes examples of successful execution, handling logs, applying security managers, loading external libraries, and managing various execution errors like timeouts and parsing failures. ```DataWeave 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": "|"}}), } ``` -------------------------------- ### Multipart::file Source: https://dataweave.mulesoft.com/learn/docs.html Creates a multipart part from a resource file located in the project path. ```APIDOC ## POST Multipart::file ### Description Creates a `MultipartPart` data structure from a resource file located in the `src/main/resources` directory. ### Method POST ### Parameters - **opts** (Object) - Required - An object containing: - **name** (String) - Required - Unique name for the Content-Disposition header. - **path** (String) - Required - Relative path to the file in `src/main/resources`. - **mime** (String) - Optional - MIME type for the content. - **fileName** (String) - Optional - Filename for the Content-Disposition header. ### Request Example ```dataweave Multipart::file({ name: "myFile", path: "myClients.json", mime: "application/json", fileName: "partMyClients.json"}) ``` ### Response - **MultipartPart** (Object) - A structured object representing a multipart part based on the file content. ``` -------------------------------- ### DataWeave Time Type Source: https://dataweave.mulesoft.com/learn/docs.html Represents a specific time, often associated with a TimeZone. Example: |22:10:18Z|. ```DataWeave Time ``` -------------------------------- ### Create a MultipartPart from a file using DataWeave Source: https://dataweave.mulesoft.com/learn/docs.html Demonstrates how to use the Multipart::file function to load an XML file from the classpath and convert it into a MultipartPart structure. This function requires parameters for the field name, file path, MIME type, and the desired filename. ```DataWeave %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" } ``` -------------------------------- ### GET dw::System::envVar Source: https://dataweave.mulesoft.com/learn/docs.html Retrieves the value of a specific environment variable from the host system. ```APIDOC ## GET dw::System::envVar ### Description Returns an environment variable with the specified name or null if the environment variable is not defined. ### Method GET ### Endpoint dw::System::envVar(variableName: String) ### Parameters #### Query Parameters - **variableName** (String) - Required - The name of the environment variable to retrieve. ### Request Example ``` import * from dw::System envVar("SHELL") ``` ### Response #### Success Response (200) - **result** (String | Null) - The value of the environment variable or null. #### Response Example ``` "/bin/bash" ``` ```