### Example DataWeave Mapping Test Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-testing-framework.adoc This example demonstrates a complete DataWeave integration test setup, including the mapping, input, configuration, expected output, and the test file itself. ```dataweave %dw 2.0 output application/json --- { hello: "world" } ``` ```dataweave { "message": "Hello world!" } ``` ```dataweave streaming=false ``` ```dataweave { "hello": "world" } ``` ```dataweave %dw 2.0 import * from dw::test::Tests import * from dw::test::Asserts --- "Test MyMapping" describedBy [ "Assert NewScenario" in do { evalPath("myPackage/MyMapping.dwl", inputsFrom("myPackage/MyMapping/NewScenario"),"application/json") must equalTo(outputFrom("myPackage/MyMapping/NewScenario")) } ] ``` -------------------------------- ### JSON Input Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-language-introduction.adoc Example of a simple JSON input structure. ```json { "message": "Hello world!" } ``` -------------------------------- ### Example Input File Content Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-multipart-functions-file.adoc This is an example of the JSON content expected in the input file (`myClients.json`) when using the `Multipart::file` function. ```JSON clients: { client: { id: 1, name: "Mariano" }, client: { id: 2, name: "Shoki" } } ``` -------------------------------- ### Example Multipart Output Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-multipart-functions-file.adoc This is an example of the generated multipart output when using the `Multipart::file` function with the provided input file and DataWeave script. ```txt ------=_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-- ``` -------------------------------- ### Input Properties File Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-formats-properties.adoc Example of a Java properties file with host and port values. ```properties host=localhost port=1234 ``` -------------------------------- ### YAML Input Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-formats-yaml.adoc This is the input YAML snippet used in the DataWeave transformation example. ```yaml american: - Boston Red Sox - Detroit Tigers - New York Yankees national: - New York Mets - Chicago Cubs - Atlanta Braves ``` -------------------------------- ### XML Output Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-language-introduction.adoc Example of the XML output produced after transforming the JSON input. ```xml Hello world! ``` -------------------------------- ### Plain Text Input Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-formats-text.adoc This is the input payload in plain text format. ```txt This is text plain ``` -------------------------------- ### application/dw Output Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-language-introduction.adoc Example of `application/dw` output from a JSON input. This format is useful for debugging as it is less strict than formats like XML. ```dataweave { size: 1, person: { name: "Yoda" } } ``` -------------------------------- ### JSON Output Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-cookbook-flat-file-read-and-write.adoc This is an example of the JSON output generated after reading and transforming a flat file. It shows the structure of the data, including batch and transaction details. ```json { "Batch": [ { "TDR": [ { "Record Type": "BAT", "Sequence Number": 2, "Amount": 32876, "Account Number": "0123456789", "Batch Function": "D", "Type": "CR" }, { "Record Type": "BAT", "Sequence Number": 3, "Amount": 87326, "Account Number": "0123456788", "Batch Function": "D", "Type": "CR" } ], "BCF": { "Record Type": "BAT", "Sequence Number": 4, "Batch Transaction Count": 2, "Batch Transaction Amount": 120202, "Unique Batch Identifier": "A000000001", "Batch Function": "T", "Type": "CR" }, "BCH": { "Record Type": "BAT", "Company Name": "ACME RESEARCH", "Sequence Number": 1, "Unique Batch Identifier": "A000000001", "Batch Function": "H" } }, { "TDR": [ { "Record Type": "BAT", "Sequence Number": 6, "Amount": 3582, "Account Number": "1234567890", "Batch Function": "D", "Type": "DB" }, { "Record Type": "BAT", "Sequence Number": 7, "Amount": 256, "Account Number": "1234567891", "Batch Function": "D", "Type": "CR" } ], "BCF": { "Record Type": "BAT", "Sequence Number": 8, "Batch Transaction Count": 2 ``` -------------------------------- ### Path Type Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-tree-types.adoc An example demonstrating the structure of a Path type, which is an array of PathElement objects. ```DataWeave [{kind: OBJECT_TYPE, selector: "user", namespace: null}, {kind: ATTRIBUTE_TYPE, selector: "name", namespace: null}] as Path ``` -------------------------------- ### Full Flat File Schema Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-flat-file-schemas.adoc A complete example of a flat file schema definition including structures, segments, groups with nested items, and elements with specific types and lengths. ```yaml form: FLATFILE structures: - id: 'BatchReq' name: Batch Request data: - { idRef: 'RQH' } - groupId: 'Batch' count: '>1' items: - { idRef: 'BCH' } - { idRef: 'TDR', count: '>1' } - { idRef: 'BCF' } - { idRef: 'RQF' } segments: - id: 'RQH' name: "Request File Header Record" values: - { name: 'Record Type', type: String, length: 3, tagValue: 'RQH' } - { name: 'File Creation Date', type: Date, length: 8 } - { name: 'File Creation Time', type: Time, length: 4 } - { name: 'Unique File Identifier', type: String, length: 10 } - { name: 'Currency', type: String, length: 3 } ``` -------------------------------- ### Object Type Examples Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-core-types.adoc Provides examples of the Object type, which represents a collection of key-value pairs. These examples demonstrate different value types within an object. ```DataWeave { myKey : "a value" } ``` ```DataWeave { myKey : { a : 1, b : 2} } ``` ```DataWeave { myKey : [1,2,3,4] } ``` -------------------------------- ### XML Input Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-streaming.adoc This is an example of an XML input document that can be processed using DataWeave streaming. ```XML
Wed Nov 15 13:45:28 EST 2006 Joe
111 2 8.90 222 7 5.20 111 2 8.90 222 7 5.20 222 7 5.20
``` -------------------------------- ### Custom Logger Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-runtime-functions-eval.adoc Illustrates the output structure when a custom logger is used, indicating success and a logged value. ```JSON { "success": true, "value": 1234, "logs": [ ] } ``` -------------------------------- ### Input XML Payload Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-cookbook-map-based-on-an-external-definition.adoc This is an example of an XML input payload that will be transformed by the DataWeave script. ```xml 1 Apple 10 2 Banana 5 3 Orange 8 ``` -------------------------------- ### XML Input for Value Selector Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-system-properties.adoc This is the XML input used in the example demonstrating the behavior of the com.mulesoft.dw.valueSelector.selectsAlwaysFirst property. ```xml chibana Shoki Shoki Tomo ``` -------------------------------- ### Output of DataWeave 'fun' Directive Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-variables.adoc Presents the JSON output generated by the DataWeave script utilizing the 'fun' directive. This confirms the equivalent results compared to the 'var' assignment examples. ```json [ { "msg": "Hello" }, { "msg2": "hello" }, { "toUpper": "hELLO" }, { "combined": "HELLO WORLD" }, { "combined2": "hello world today" } ] ``` -------------------------------- ### Input JSON for 'if-else' Example (with value) Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-cookbook-defaults.adoc This input JSON has a value for the 'location' field, which will be used directly. ```json { "location": "Canada" } ``` -------------------------------- ### Example Diff with No Differences Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-diff-types.adoc Illustrates the output of a Diff type when two values are identical. ```JSON { "matches": true, "diffs": [ ] } ``` -------------------------------- ### Example Custom Module for Aliasing Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-create-module.adoc A sample custom module defining a function and a variable, used to demonstrate aliasing. ```dataweave %dw 2.0 fun myFunc(name:String) = name ++ "_" var myVar = "Test" ``` -------------------------------- ### Default Output Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-runtime-functions-eval.adoc Shows the structure of a default output in DataWeave, including success status, value, and logs. ```JSON { "success": true, "value": { "name": "Mariano", "lastName": "achaval" }, "logs": [ ] } ``` -------------------------------- ### Output JSON for 'if-else' Example (with value) Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-cookbook-defaults.adoc The output JSON shows the 'userLocation' mapped from the input 'location' field. ```json { "userLocation": "Canada" } ``` -------------------------------- ### Create Multipart Parts with Comma-Separated Syntax Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-multipart-functions-field.adoc This example demonstrates creating multipart parts using the comma-separated argument syntax for the Multipart::field function. It generates a JSON part with a file name and an XML part without one, similar to the previous example but using a different argument passing style. ```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") } } ``` -------------------------------- ### Get Function Parameters with functionParamTypes Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-types-functions-functionparamtypes.adoc Use functionParamTypes to extract parameter details from defined function types. This example demonstrates its behavior with functions having different parameter signatures. ```DataWeave %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) } ``` ```Json { "a": [ { "paramType": "String", "optional": false }, { "paramType": "Number", "optional": false } ], "b": [ ] } ``` -------------------------------- ### Get Function Return Type with functionReturnType Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-types-functions-functionreturntype.adoc Use functionReturnType to determine the return type of a defined function. This example demonstrates its behavior with two different function types. ```DataWeave %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) } ``` -------------------------------- ### Create Multipart Data Structure with Files and Fields Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-multipart-functions-form.adoc This example demonstrates creating a multipart data structure with three parts: one file part imported from 'orders.xml', one field part using an object for parameters, and another field part using positional parameters. It shows how to specify mime types and filenames. ```DataWeave %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") ]) ``` ```json ------=_Part_146_143704079.1560394078604 Content-Type: application/xml Content-Disposition: form-data; name="file"; filename="myorders.xml" 1001 1 $100 2001 2 $50 ------=_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-- ``` -------------------------------- ### Extract a Value from a JSON Object with Pluck Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-cookbook-pluck.adoc Extract a specific value from a JSON object using the pluck function with a key. This example shows how to get the 'dept' value. ```DataWeave %dw 2.0 output application/json -- payload pluck "dept" ``` -------------------------------- ### Output JSON for 'default' Keyword Example (using defaults) Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-cookbook-defaults.adoc The output JSON shows the default values 'guest' and 'Anonymous' because the input fields were missing. ```json { "userId": "guest", "userName": "Anonymous" } ``` -------------------------------- ### String Splitting with splitBy Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-core-functions-splitby.adoc Demonstrates splitting strings using different separators. The first example splits by an empty string, the second by a comma, and the third by a separator not present in the string. ```dw %dw 2.0 output application/json --- { splitters: { "split1" : [ "a","b","c" ], "split2" : "hello world" splitBy(""), "split3" : "first,middle,last" splitBy(","), "split4" : "no split" splitBy("NO") } } ``` -------------------------------- ### Valid Identifiers in DataWeave Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-language-introduction.adoc Examples of valid and invalid identifiers in DataWeave. Valid identifiers must start with a letter, followed by letters, numbers, or underscores, and cannot be reserved keywords. ```text myType abc123 a1_3BC_22 Z_______4 F ``` ```text 123456 | Cannot start with a number. value$ | Cannot contain special characters. _number | Cannot start with an underscore. type | Cannot be a reserved keyword. ``` -------------------------------- ### DataWeave toLocalDateTimeOrNull Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-coercions-functions-tolocaldatetimeornull.adoc Demonstrates the behavior of toLocalDateTimeOrNull with matching and non-matching formatters. Requires importing dw::util::Coercions. ```DataWeave %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"}]) } ``` -------------------------------- ### Trim leading and trailing spaces from a string Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-core-functions-trim.adoc This example demonstrates the basic usage of the trim() function to remove whitespace from the start and end of a string. Spaces within the string are preserved. ```DataWeave %dw 2.0 output application/json --- { "trim": trim(" my really long text ") } ``` -------------------------------- ### Specify Type Parameters for a Function Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-functions-lambdas.adoc Starting with DataWeave 2.5, specify function type parameters at the call site. This example shows a generic `max` function for an array of numbers. ```json { "measures": [1,2,4,1,5,2,3,3] } ``` ```dataweave %dw 2.5 output application/json fun max(elems: Array): T = elems reduce ((candidate: T, currentMax = elems[0]) -> if (candidate > currentMax) candidate else currentMax) --- { max: max(measures) } ``` ```json { "max": 5 } ``` -------------------------------- ### Dynamically Generated Namespace Values in DataWeave Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-cookbook-include-xml-namespaces.adoc Support starting in Mule version 4.2.1. This example shows how to output values for namespace keys and attributes using input defined in DataWeave variables. ```dataweave %dw 2.0 output application/xml var nsMap = { "ns0": "http://example.org/ns0", "ns1": "http://example.org/ns1" } var nsKey = "ns0" var nsAttr = "ns1" --- "content" ``` -------------------------------- ### Get Data Format Descriptors Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-runtime-functions-dataformatsdescriptor.adoc This snippet demonstrates how to retrieve an array of all installed DataFormatDescriptor values using the `dataFormatsDescriptor()` function. The output shows the detailed properties of JSON and XML data formats. ```DataWeave import * from dw::Runtime --- dataFormatsDescriptor() ``` ```Json [ { "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 ] } ] } ] ``` -------------------------------- ### Parameterized Type Definitions for File Handling Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-type-system.adoc This example shows how to parameterize type definitions to model different file content types (String and Binary) and how to use overloaded functions to read them. ```DataWeave %dw 2.0 type FileData = { data: Content, name: String } fun read(file: FileData) = "This is a text file with data " ++ file.data fun read(file: FileData) = "This is a binary file with data " ++ (file.data as String {base: "64"}) --- { binary: read({data: "Hello World" as Binary, name: "myFile.bin"}), text: read({data: "Hello World", name: "myFile.txt"}) } ``` -------------------------------- ### Object Type Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-types.adoc A basic example of an Object type with a single key-value pair. ```dataweave %dw 2.0 output application/json --- { name: "Annie" } ``` -------------------------------- ### Function Composition using Prefix Notation Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-language-guide.adoc Achieves the same result as the previous example but uses prefix notation to explicitly show how the 'filter' function takes the output of the 'pluck' function as its first parameter. ```dataweave %dw 2.0 output application/json var collaborators = { Max: {role: "admin", id: "01"}, Einstein: {role: "dev", id: "02"}, Astro: {role: "admin", id: "03"}, Blaze: {role: "user", id: "04"} } --- filter( pluck( collaborators, (value,key,index)-> { "Name": key, "Role": upper(value.role), "ID": value.id }), (item, index) -> item.Role == "ADMIN") ``` -------------------------------- ### toString() Function Examples Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-coercions-functions-tostring.adoc Demonstrates various uses of the toString() function with different number inputs, formats, locales, and rounding modes. ```DataWeave %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'") } ``` -------------------------------- ### Execute DataWeave Script with Inputs Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-runtime-functions-run.adoc Demonstrates basic execution of a DataWeave script with JSON input. The `run` function executes the specified file (`main.dwl`) using the provided file system and input values. ```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": "|"}}) } ``` -------------------------------- ### PathElement Type Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-tree-types.adoc An example illustrating a PathElement, specifically for selecting an element within an array. ```DataWeave {kind: ARRAY_TYPE, selector: "name", namespace: null} as PathElement ``` -------------------------------- ### Output JSON for 'default' Keyword Example (with values) Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-cookbook-defaults.adoc The output JSON shows the mapped values from the input payload when 'id' and 'name' are present. ```json { "userId": 123, "userName": "John Doe" } ``` -------------------------------- ### Reverse String Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-strings-functions-reverse.adoc Demonstrates the behavior of the reverse() function with different string inputs, including a regular string, null, and an empty string. ```DataWeave %dw 2.0 import * from dw::core::Strings output application/json --- { a: reverse("Mariano"), b: reverse(null), c: reverse("") } ``` -------------------------------- ### Import All Types from Avro Schema Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-type-reuse-avro-schema.adoc Use this syntax to import all types defined in an Avro schema file. Replace `example::schema::User` with the actual path to your schema file, using `::` as a separator and omitting the file extension. ```DataWeave import * from avroschema!example::schema::User ``` -------------------------------- ### Example COBOL Copybook Definition Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-formats-copybook.adoc This is an example of a COBOL copybook definition file (`mailing-record.cpy`) that describes the structure of a mailing record. ```cobol 01 MAILING-RECORD. 05 COMPANY-NAME PIC X(30). 05 CONTACTS. 10 PRESIDENT. 15 LAST-NAME PIC X(15). 15 FIRST-NAME PIC X(8). 10 VP-MARKETING. 15 LAST-NAME PIC X(15). 15 FIRST-NAME PIC X(8). 10 ALTERNATE-CONTACT. 15 TITLE PIC X(10). 15 LAST-NAME PIC X(15). 15 FIRST-NAME PIC X(8). 05 ADDRESS PIC X(15). 05 CITY PIC X(15). 05 STATE PIC XX. 05 ZIP PIC 9(5). ``` -------------------------------- ### Manually Construct Multipart Data Structure Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-multipart-functions-form.adoc This example shows how to manually construct a data structure compatible with the 'multipart/form-data' output format without using the 'form' function. Note that part keys like 'part1' and 'part2' are stripped in the final output. ```DataWeave %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) } } ``` ```txt ------=_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 Unit Test for a Module Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-testing-framework.adoc This DataWeave file demonstrates how to structure a unit test for a custom module. It includes necessary imports and a sample test case with an assertion. ```dataweave %dw 2.0 import * from dw::test::Tests import * from dw::test::Asserts import * from MyModule --- "MyModule" describedBy [ "something" describedBy [ "It should do something" in do { something() must beObject() }, ], ] ``` -------------------------------- ### TimeFactory Type Definition and Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-dates-types.adoc Defines the TimeFactory type by combining LocalTimeFactory and Zoned types. An example illustrates how to create a TimeFactory value. ```dw type TimeFactory = LocalTimeFactory & Zoned {hour: 8, minutes: 31, seconds: 55, timeZone : |-03:00|} as TimeFactory ``` -------------------------------- ### Handle various string inputs with trim() Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-core-functions-trim.adoc This example illustrates how the trim() function behaves with different types of string inputs, including null, empty strings, strings containing only spaces, strings with no spaces, and strings with leading/trailing spaces. ```DataWeave %dw 2.0 output application/json --- { "null": trim(null), "empty": trim(""), "blank": trim(" "), "noBlankSpaces": trim("abc"), "withSpaces": trim(" abc ") } ``` -------------------------------- ### LocalDateTimeFactory Type Definition and Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-dates-types.adoc Defines the LocalDateTimeFactory type by combining DateFactory and LocalTimeFactory. The timeZone field is optional. An example demonstrates its construction. ```dw type LocalDateTimeFactory = DateFactory & LocalTimeFactory {day: 21, month: 1, year: 2021, hour: 8, minutes: 31, seconds: 55, timeZone : |-03:00|} as LocalDateTimeFactory ``` -------------------------------- ### evalUrl Function Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-runtime-functions-evalurl.adoc Demonstrates the usage of the evalUrl function with different input methods. It shows how to execute a script from a classpath URL, passing data via readerInputs and inputValues. ```DataWeave %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"}}) } ``` -------------------------------- ### Importing All Functions from a Module and Calling Them Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-functions.adoc Illustrates importing all functions from dw::core::Strings using the wildcard and calling the pluralize function directly. This is convenient when you need many functions from a module. ```dataweave %dw 2.0 import * from dw::core::Strings output application/json --- { 'plural': pluralize("box") } ``` -------------------------------- ### DateTimeFactory Type Definition and Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-dates-types.adoc Defines the DateTimeFactory type by combining DateFactory, LocalTimeFactory, and Zoned types. An example shows how to construct a DateTimeFactory value. ```dw type DateTimeFactory = DateFactory & LocalTimeFactory & Zoned {day: 21, month: 1, year: 2021, hour: 8, minutes: 31, seconds: 55, timeZone : |-03:00|} as DateTimeFactory ``` -------------------------------- ### Array Type Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-core-types.adoc Illustrates the Array type, which can hold elements of any specified type. The example shows an array containing various data types. ```DataWeave [1, 2, "a", "b", true, false, { a : "b"}, [1, 2, 3] ] ``` -------------------------------- ### Pipe-separated CSV Input Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-cookbook-reader-prop-connector.adoc This is an example of a CSV input where the pipe symbol (|) is used as a separator instead of a comma. It includes a header row and data with commas within fields. ```csv id | name | role 1234 | Shokida,Mr. | dev 2345 | Achaval,Mr. | arch 3456 | Felisatti,Ms. | mngr 4567 | Chibana,Mr. | dev ``` -------------------------------- ### DataWeave rightPad Function Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-strings-functions-rightpad.adoc Demonstrates the behavior of the rightPad function with various inputs, including null, empty strings, and strings requiring different padding amounts. It also shows behavior with negative sizes. ```DataWeave %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) } ``` -------------------------------- ### startsWith(text: String, prefix: String): Boolean Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-core-functions-startswith.adoc Returns true or false depending on whether the input string starts with a matching prefix. This function can be invoked using either `startsWith(text, prefix)` or the more concise `text startsWith(prefix)` notation. ```APIDOC ## startsWith(text: String, prefix: String): Boolean ### Description Returns `true` or `false` depending on whether the input string starts with a matching prefix. This function can be invoked using either `startsWith(text, prefix)` or the more concise `text startsWith(prefix)` notation. ### Parameters #### Path Parameters - **text** (String) - Required - The input string. - **prefix** (String) - Required - 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")`). ==== Source ```DataWeave %dw 2.0 output application/json --- [ "Mari" startsWith("Mar"), "Mari" startsWith("Em") ] ``` ==== Output ```JSON [ true, false ] ``` ``` -------------------------------- ### JSON Streaming Example Output Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-formats-json.adoc This is the output of a JSON streaming example, showing an array of objects with zipcode values. It is generated when the File Read operation is configured to stream JSON input. ```json [ { "returnedElement": "95838" }, { "returnedElement": "95823" }, { "returnedElement": "95815" }, { "returnedElement": "95815" }, { "returnedElement": "95824" }, { "returnedElement": "95841" } ] ``` -------------------------------- ### Use String Repeat Function Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-type-system.adoc Demonstrates the usage of the 'repeat' function from the String module, which takes a string and a number to repeat the string. The example shows a successful call with valid types. ```DataWeave %dw 2.0 import * from dw::core::Strings output application/json --- repeat("a", 3) ``` -------------------------------- ### Sample Flat File Data Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-flat-file-schemas.adoc This is a sample of data that matches a defined flat file schema. It demonstrates the structure of request files with headers, batch details, transaction records, and footers. ```text RQH201809011010A000000001USD BAT000001HACME RESEARCH A000000001 BAT000002D01234567890000032876CR BAT000003D01234567880000087326CR BAT000004T0000120202CR000002A000000001 BAT000005HAJAX EXPLOSIVES A000000002 BAT000006D12345678900000003582DB BAT000007D12345678910000000256CR BAT000008T0000003326DB000002A000000002 RQF0002000008000000116876CRA000000001 ``` -------------------------------- ### Get Current DateTime and Specific Time Zone Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-core-functions-now.adoc Demonstrates how to get the current date and time using now() and how to specify a time zone for the output. Supports Java 17 time zones. ```DataWeave %dw 2.0 output application/json --- { nowCalled: now(), nowCalledSpecificTimeZone: now() >> "America/New_York" } ``` -------------------------------- ### Find Index of Element Starting with 'Jul' Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-arrays-functions-indexwhere.adoc Use indexWhere to find the index of the first element in an array that meets a specific condition, such as starting with a particular string. Returns -1 if no match is found. ```DataWeave %dw 2.0 import * from dw::core::Arrays output application/json var users = ["Mariano", "Leandro", "Julian"] --- users indexWhere (item) -> item startsWith "Jul" ``` -------------------------------- ### Check if strings start with a prefix Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-core-functions-startswith.adoc Demonstrates how to use the startsWith function to check if strings begin with a given prefix. Supports both direct and infix notation. ```DataWeave %dw 2.0 output application/json --- [ "Mari" startsWith("Mar"), "Mari" startsWith("Em") ] ``` -------------------------------- ### Test Response for Java Bridge Example Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-cookbook-java-methods.adoc This is the expected JSON response from the Mule application when the Java bridge example is tested with a specific URI parameter. It shows the greeting message generated by the Java code. ```json { "response": "Greetings, Username!" } ``` -------------------------------- ### Split String by Multiple Separators Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-core-functions-splitby.adoc Demonstrates splitting strings using different string separators. Includes splitting by hyphen, empty string (to split characters), and comma. Also shows a case-sensitive separator that does not match. ```DataWeave %dw 2.0 output application/json --- { "splitters" : { "split1" : "a-b-c" splitBy("-"), "split2" : "hello world" splitBy(""), "split3" : "apple,banana,cherry" splitBy(","), "split4" : "NO match" splitBy("no") } } ``` -------------------------------- ### TimeMeasurement Type Definition Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-timer-types.adoc Defines a structure to capture the start time, end time, and the result of a function. This type is useful for detailed timing analysis, including the exact start and end points of an operation. ```DataWeave type TimeMeasurement = { start: DateTime, result: T, end: DateTime } ``` -------------------------------- ### between(endDateExclusive: Date, startDateInclusive: Date): Period Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-periods-functions-between.adoc 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`). ```APIDOC ## between(endDateExclusive: Date, startDateInclusive: Date): Period ### Description 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`). ### Parameters #### Path Parameters - **endDateExclusive** (Date) - Required - The end date, exclusive. - **startDateInclusive** (Date) - Required - The start date, inclusive. ### Example This example shows `between` behavior with different inputs. ==== Source ```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|) } ``` ==== Output ```json { "a": "P2D", "b": "P1Y1M1D", "c": "P-1M-1D" } ``` ``` -------------------------------- ### Encode URI Components with encodeURIComponent and encodeURI Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-url-functions-encodeuricomponent.adoc This example demonstrates the difference between encodeURIComponent and encodeURI by encoding various URI components. It shows which characters are escaped by each function. ```DataWeave %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("-_.!~*'()") } } ``` -------------------------------- ### Example of TimeZone Format Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-types.adoc Represents a TimeZone offset from GMT, including a sign. ```dataweave |-08:00| ``` -------------------------------- ### Example of Time Format Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dataweave-types.adoc Represents a time in HH:mm:ss format. ```dataweave |23:59:56| ``` -------------------------------- ### Unzip an array of arrays with matching elements Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-core-functions-unzip.adoc This example demonstrates unzipping an array of arrays where each sub-array has the same number of elements. It outputs arrays based on the indices of the sub-arrays. ```DataWeave %dw 2.0 output application/json --- ``` ```DataWeave unzip([ [0,"a"], [1,"b"], [2,"c"],[ 3,"d"] ]) ``` -------------------------------- ### Assert String Starts With Prefix Source: https://github.com/mulesoft/docs-dataweave/blob/v2.11/modules/ROOT/pages/dw-test-asserts.adoc Validates that a string begins with a specified prefix. ```DataWeave %dw 2.0 import dw::tests::Asserts --- "A Text" must startWith("A") ```