DataWeave Quickstart | MuleSoft Documentation (2024)

  1. Homepage
  2. DataWeave (2.7)
  3. DataWeave Quickstart

In this guide, you run DataWeave 2.0 scripts on sample data, without relyingon external data sources.Before you begin, note that 2.x versions of DataWeave are used by Mule 4 apps. ForDataWeave in Mule 3 apps, refer to theDataWeave version 1.2 documentation.For other Mule versions, you can use the version selector in the DataWeave table of contents.

The examples introduce some key DataWeave conceptsthat you can explore further whenever you are ready, and they show how to turnthe Transform Message component into a DataWeave playground.

To run the scripts, you copy them into the source code area of a TransformMessage component in Studio, then view the resultsin the component’s Preview pane. You also load content from files so thatyour DataWeave script can act on it. Once you feel comfortable with DataWeaveexamples here and elsewhere in the docs, you can use the DataWeave playgroundto practice writing your own DataWeave scripts on sample data.

DataWeave Quickstart | MuleSoft Documentation (1)

The figure shows a Transform Message component in the center canvas, within testingscriptFlow. Below the Studio canvas, the Transform Message tabincludes a DataWeave script in the source code area with output in thePreview pane.

Prerequisites

Studio 7 is required.Versions 7.3 or 7.2.3 are recommended. Other Studio 7 versions are untestedwith this guide.

Once Studio is installed, you need to set up a project with a Transform Message component. See Set Up a Project in Studio.

Set Up a Project in Studio

Set up a Mule project that serves as a DataWeave playground:

  1. In Studio, click FileNewMule Project to create a Mule project.

  2. Provide the name testscript for the project, and click Finish.

  3. From the Mule Palette tab of your new project, click Core, and then drag the Transform Message component into the Studio canvas.

    DataWeave Quickstart | MuleSoft Documentation (2)

    (A) Mule Palette tab

    (B) Studio canvas with Transform Message component

    (C) Transform Message tab

  4. In the Transform Message tab, click Preview (on the far right) to openthe Preview pane, and click the empty rectangle next to Preview to expandthe source code area.

    DataWeave Quickstart | MuleSoft Documentation (3)

    The source code area on the left is the place where you are going to addDataWeave scripts, and the Preview pane on the right is where you view theoutput of the scripts.

  5. Proceed to Start Scripting.

Start Scripting

  1. Concatenate Two Strings into a Single String

  2. Transform JSON Input to XML Output

  3. Learn About Supported Data Types

  4. Define and Use a DataWeave Variable as Input

  5. Use a DataWeave Function in a DataWeave Variable

  6. Read, Transform, and Select Content from an Input

  7. Read File Contents with a DataWeave Function

  8. Map Elements from an Array into an Object

  9. Pluck Values from an Object into an Array

  10. Map and Merge Fields

Concatenate Two Strings into a Single String

Begin with a simple DataWeave script that concatenates two strings ("hello" and"World") together into a single string ("helloWorld").

DataWeave Quickstart | MuleSoft Documentation (4)

  1. Replace the current script in the source code area of the Transform Messagetab with this one:

    %dw 2.0output application/json---{ myString: ("hello" ++ "World") }
    • The body of the DataWeave script contains a key-value pair({ myString: ("hello" ++ "World") }). The value of this input objectis a DataWeave expression (("hello" ++ "World")) for concatenatingthe strings "hello" and "World" into a single string, "helloWorld".

      When you are ready, you can learn about the DataWeave++ function used to concatenate the strings.

    • The header of the script is all the content above the three dashes, ---.It includes important directives, including one for specifying the output formatapplication/json. You can learn more aboutDataWeave Scripts when you are ready.

  2. See the JSON output in the Preview pane:

    { "myString": "helloWorld" }
  3. Proceed to Transform JSON Input to XML Output.

Transform JSON Input to XML Output

Many integrations require transformations from one format to another. Thisprocedure uses the output directive to produce XML output from JSON input.

DataWeave Quickstart | MuleSoft Documentation (5)

  1. Replace the body of the current script in the source code area with JSON output from Concatenate Two Strings into a Single String, and change the output application/json directive to output application/xml:

    %dw 2.0output application/xml---{ "myString" : ("helloWorld") }
  2. See the XML output in the Preview pane:

    <?xml version='1.0' encoding='UTF-8'?><myString>helloWorld</myString>

    Notice that the "myString" key of the input JSON object{ "myString" : ("helloWorld") } is converted to the root element of theXML output and that the concatenated string becomes the value of that XMLobject. So the XML output is <myString>helloWorld</myString>. That output ispreceded by a standard XML declaration that specifies the XML version and encoding.

    Without a single key to serve as a root node for XML output (for example,if the input is simply ("helloWorld")), the transformation to XML willfail with a yellow warning (!) in the source code area. The warning messageis Trying to output non-whitespace characters outside main element tree. Ifyou like, you can try to produce this warning on your own.

    DataWeave supports many output and input formats. You can learn more aboutSupported Data Formats when you are ready.

  3. Proceed to Learn About Supported Data Types

Learn About Supported Data Types

Now provide a DataWeave script that simply introduces you to a variety ofsupported data types and shows how to add comments to a script.

  1. Replace the current script in the source code area of the Transform Messagetab with this one:

    %dw 2.0output application/json---{ /* * A multi-line * comment here. */ myString: "hello world", myNumber: 123, myFloatingPointNumber: 123.456, myVeryBigNumber: 12341234134123412341234123, myDate: |2018-12-07|, myTime: |11:55:56|, myDateTime: |2018-10-01T23:57:59-03:00|, myBoolean: true, myArray: [ 1, 2, 3, 5, 8], myMixedArray: [ 1, 2, "blah", { hello: "there" } ], myObjectKeyValuePair: { innerKey: "innerValue" }, myObjectWithConditionalField: { a : { b : 1, ( c : 2 ) if true, (d : 4) if false } }, myNull: null, myBinary: "abcd1234123" as Binary //A one-line comment here.}

    DataWeave supports multi-line comments within /* */ markup and single-linecomments after forward slashes (//). It also supports many data types, shownafter the colon (:) in key-value pairs, such as myString: "hello world" andmyNumber: 123. These types include strings (surrounded by quotation marks,""), numbers, date and time structures (within pipes, ||), Booleans (trueand false), arrays (within square brackets, []), JSON-like objects(key-value structures within curly braces, {}), null, and binaries. Whenyou are ready for more on this topic, you can reviewDataWeave types.

  2. See the JSON output in the Preview pane:

    { "myString": "hello world", "myNumber": 123, "myFloatingPointNumber": 123.456, "myVeryBigNumber": 12341234134123412341234123, "myDate": "2018-12-07", "myTime": "11:55:56", "myDateTime": "2018-10-01T23:57:59-03:00", "myBoolean": true, "myArray": [ 1, 2, 3, 5, 8 ], "myMixedArray": [ 1, 2, "blah", { "hello": "there" } ], "myObjectKeyValuePair": { "innerKey": "innerValue" }, "myObjectWithConditionalField": { "a": { "b": 1, "c": 2 } }, "myNull": null, "myBinary": "abcd1234123"}
  3. Proceed to Define and Use a DataWeave Variable as Input

Define and Use a DataWeave Variable as Input

Now try a simple DataWeave script that outputs the value of the DataWeavevariable myJson. You set the variable using the var directive in thescript’s header.

  1. Replace the current script in the source code area of the Transform Messagetab with this one:

    %dw 2.0var myJson = { "hello" : "world" }output application/json---myJson

    A JSON object ({ "hello" : "world" }) is defined as the myJson variable inthe script’s header. You can learn more aboutDataWeave Variables when you are ready.

  2. See the output in the Preview pane:

    { "hello": "world"}
  3. Proceed to Use a DataWeave Function in a DataWeave Variable

Use a DataWeave Function in a DataWeave Variable

Now try a script that uses the DataWeave avg function in a DataWeavevariable (myJson) to get averages of two sets of numbers.

DataWeave Quickstart | MuleSoft Documentation (6)

  1. Replace the current script in the source code area with this one:

    %dw 2.0var myJson = { a: avg([1, 1000]), b: avg([1, 2, 3])}output application/json---myJson

    The avg functions here get invoked when you add myJson to the body of thescript, producing the calculated averages within the JSON object you can see inthe Preview pane. The structures [1, 1000] and [1, 2, 3] arearrays. You can learn more aboutavg when you are ready.

  2. Preview the output:

    { "a": 500.5, "b": 2.0}
  3. Proceed to Read, Transform, and Select Content from an Input

Read, Transform, and Select Content from an Input

Now try a more complicated script that reads XML input, transforms it toJSON, and only selects the contents of the car element.

  1. Replace the current script in the source code area with this one:

    %dw 2.0var myRead = read("<car><color>red</color></car>", "application/xml")output application/json---{ mySelection : myRead.car}

    If you encounter an issue previewing this example, try changing myRead.carto myRead."car". Learn more about the readfunction, Supported Data Formats, andDataWeave Selectors when you are ready.

  2. Preview the output:

    { "mySelection": { "color": "red" }}
  3. Proceed to Read File Contents with a DataWeave Function

Read File Contents with a DataWeave Function

Now use readUrl to read the contents of a file in the Studiosrc/main/resources folder so you can use that content as sample data for aDataWeave script.

  1. Add a file by right-clicking the src/main/resources folder in thePackage Explorer tab, then navigating to NewFile, providing the filename myJson.json for that file, and clicking Finish.

  2. From src/main/resources, provide and save the following sample content inthe myJson.json tab (or within the Source sub-tab of the myJson.json tab,if it is present):

    { "hello": "world"}

    DataWeave Quickstart | MuleSoft Documentation (7)

    Figure 1. myJson.json in Studio

  3. Returning to the Transform Message component within the testscripttab, replace the current script with one that uses readUrl to read the JSONcontents from your file:

    %dw 2.0output application/json---readUrl("classpath://myJson.json", "application/json")

    Learn more about the readUrl function whenyou are ready.

  4. View the matching output in the Preview pane.

    { "hello": "world"}

    Note that you can also load the contents of a file through a metadata type inthe Transform Message component. That procedure is covered later, inRun Examples with Longer Payloads. It uses the myJson.json file you just created.

  5. Proceed to Map Elements from an Array into an Object

Map Elements from an Array into an Object

Almost all integrations require data mappings. Here, you map elements withinan array to keys and values of a JSON object:

  1. Replace the current script in the source code area with this one:

    %dw 2.0output application/json---{ ( ["a", "b", "c"] map ((value, index) -> { (index): value }) )}

    The map function iterates over the array on the left to apply the lambda(anonymous function) on the right (((value, index) → { (index): value }))to elements in that array. The lambda usesnamed parameters(value and index) to select the values and indices from thearray and populate a JSON object with key-value pairs. Learn aboutmap, and when you are ready, compare mapwith mapObject, which takes an object asinput.

  2. Preview the output:

    { "0": "a", "1": "b", "2": "c"}
  3. Proceed to Pluck Values from an Object into an Array

Pluck Values from an Object into an Array

Now use the DataWeave pluck function to iterate over values in a JSONobject and output those values into an array.

  1. Replace the contents of the source code area with a script that usespluck on a JSON object:

    %dw 2.0output application/json---{ "0": "a", "1": "b", "2": "c"} pluck ((value) -> value)

    Notice that the input object matches the outputof the map example and that the output array matches the inputfrom the map example. Learn more about pluckwhen you are ready.

  2. Preview the output:

    [ "a", "b", "c"]
  3. Proceed to Map and Merge Fields.

Map and Merge Fields

Now try a more complex example that maps and merges fields from items inseparate arrays. The point here is simply to provide a taste of DataWeave’sability to handle more complex mappings and transformations needed for someintegrations.

  1. Replace the current script in the source code area with this one:

    %dw 2.0var myVar = [ { bookId: 101, title: "world history", price: "19.99" }, { bookId: 202, title: 'the great outdoors', price: "15.99" }]var myVar2 = [ { bookId: 101, author: "john doe" }, { bookId: 202, author: "jane doe" }]output application/json---myVar map (item, index) -> using (id = item.bookId) {"id" : id,"topic" : item.title,"cost" : item.price as Number,(myVar2 filter ($.*bookId contains id) map (item) -> {author : item.author})}

    When you are ready to explore the language further, you can learn how thefilter function used near the end returnsauthor values from the array in the myVar2 variable. You can read abouttype coercion with DataWeave to see howas works with the data type in the line "cost" : item.price as Number, tocoerce input strings like "19.99" into numbers like 19.99. You can see howusing (shown in using (id = item.bookId)) enables you to createlocal DataWeave variables in ascript.

  2. Preview the output:

    [ { "id": "101", "topic": "world history", "cost": 19.99, "author": "john doe" }, { "id": "202", "topic": "the great outdoors", "cost": 15.99, "author": "jane doe" }]
  3. Proceed to Try Out More DataWeave Examples.

Try Out More DataWeave Examples

Now you are ready to run DataWeave examples on your own. In your DataWeaveplayground, you can run examples from the docs whenever you want to discovermore about the DataWeave language. You can play with the examples and use themto start your own scripts.

For examples that use payload to reference input data (such as thecontains ormapObject function examples), youcan avoid payload-related issues by using techniques described in Run Examples that Act on a Payload.
  1. Find many more examples to try out in Studio here:

    • DataWeave Operators

    • DataWeave Reference: Docs on the DataWeave functionmodules provide many examples that use DataWeave functions.

    • Flow Control in DataWeave

    • Pattern Matching in DataWeave

    • DataWeave Cookbook

    • Define DataWeave Functions

  2. Proceed to Next Steps.

Run Examples that Act on a Payload

In DataWeave, payload is a built-in Mule Runtime variable that holds thecontents of a Mule message. It enablesyou to retrieve the body of a message simply by typing payload into theDataWeave script. The docs often refer to this content as "the payload."

To try out DataWeave examples that use payload to get the contents of aMule message, you have some options:

  • Run Examples with Short Payloads: You can use a DataWeave variable.

  • Run Examples with Longer Payloads: Add the payload content through a file. This techniquealso works for short payloads.

Alternatives that require a running Mule app (such as usingSet Payload) are not covered herebut are introduced in Next Steps.

Run Examples with Short Payloads

For short examples with a few lines of sample data, you can convert the inputpayload to a variable. You simply copy the payload’s content into a DataWeavevariable (var) in the header of a DataWeave script. Then, in the body of thescript, you replace payload with the name of the new variable to referencethat variable.

  1. Start with this script in the source code area:

    %dw 2.0output application/json---ContainsRequestedItem: payload.root.*order.*items contains "3"

    Notice that you cannot preview it yet:

    DataWeave Quickstart | MuleSoft Documentation (8)

  2. Now modify this example so that it uses some sample inputinstead of attempting to use payload to input content of a Mule message thatdoes not exist:

    1. Add a myInput DataWeave variable supplying some input data the script canread, and change the Mule payload variable in the body of the script to theDataWeave myInput variable.

      %dw 2.0var myInput = read("<root> <order> <items>1</items> <items>3</items> </order> <order> <items>2</items> </order></root>","application/xml")output application/json---ContainsRequestedItem: myInput.root.*order.*items contains "3"
    2. Preview the results:

      { "ContainsRequestedItem": true}

      When you are ready, learn more about thecontains functionand about the built-in payload variable, inPredefined Variables.

Run Examples with Longer Payloads

For DataWeave examples with many lines of sample data, consider creating ametadata type through Transform Message. Metadata types can accept alocal file that contains sample data.

  1. Use the readUrl example to create src/main/resources/myJson.json in Studio.

    You can skip this step if you still have the file in Studio. The next stepsshow how to use the contents of this file as your payload.

  2. Now replace the current script from the source code area of theTransform Message with one that selects the payload of the input:

    %dw 2.0output application/json---payload
  3. Notice that you cannot preview a payload now because it does not exist yet.

    DataWeave Quickstart | MuleSoft Documentation (9)

  4. Now provide a simple JSON object as the payload of the Transform Message:

    1. In the Transform Message tab, click the left-most rectangle from thePreview button to open the columned, graphical view next to the sourcecode area:

      DataWeave Quickstart | MuleSoft Documentation (10)

      If you mouse over that rectangle, you can see the label Show Graphic.

    2. In the left-most column of the Transform Message tab, find Payload: Unknown, and click Define metadata.

      If you do not see the Define metadata link, simply right-click the Payload:entry in the left-most column, and then click Set Metadata to open theSelect metadata type dialog.

  5. Now load the contents of myJson.json (created inthe readUrl example) into the Transform Message component:

    1. Click +Add to open the Create new type dialog.

    2. In the dialog, provide the Type id myJsonType, and click Create type.

      DataWeave Quickstart | MuleSoft Documentation (11)

    3. Back in the Select metadata type dialog that opens, select JSON fromthe Type drop-down menu.

      DataWeave Quickstart | MuleSoft Documentation (12)

    4. Below the new type, change Schema to Example (as shown above).

    5. Use the navigation button with the ellipsis (…​) to find src/main/resources/myJson.json, and click Open, which displays thestructure of the file contents (hello: String) in the Select metadata type window.

    6. Now click Select to load the contents of the file into the messagepayload.

    7. Notice that the JSON object from myJson.json is now in the Preview pane.

      If necessary, you can click Preview to open the Preview pane.

    8. Now click the empty rectangle next to the Preview button to open the source code area, and change the body of the script to payload.hello,retaining the existing DataWeave header content.

      Notice that the Preview pane now contains only the value of the payload:"world".

      Here is what this example looks like in Studio:

      DataWeave Quickstart | MuleSoft Documentation (13)

      Learn more about DataWeave Selectorswhen you are ready.

Next Steps

  • To get started with Mule app development and data mapping through theStudio UI, see Tutorial: Create a Mule app that uses the Database Connector and DataWeave.

  • Beyond the Transform Message component, many Mule connectors, modules, andCore components accept DataWeave selectors and short DataWeave expressionsin their fx fields.

    To learn about the components, you can start fromMule Components.

    To try out sample data in a running Mule app, without relying on externaldata sources, you can use these Core components with or without TransformMessage:

    • Set Payload to providecontent for the payload of a Mule event.

    • Set Variable to create content ina Mule event variable.

    • Scheduler to trigger the regular generation of Mule events.

    • Logger to view output and issues loggedin the Studio console.

Here is an example that uses some of these components:

DataWeave Quickstart | MuleSoft Documentation (14)

  • The fx value of Set Payload is set to output application/json --- { hello : "world"}.

  • The fx value of the Logger is set to payload, which looks like #[payload] in the UI and the XML configuration file for the project.

  • The Console tab of the running Mule app (testscript) displays the payload from Set Payload.

DataWeave Quickstart | MuleSoft Documentation (2024)

References

Top Articles
1533 Galleria Boulevard, Rock Hill, SC 29730
QuikTrip Corporation > QT Cards
Pinellas County Jail Mugshots 2023
The Atlanta Constitution from Atlanta, Georgia
Kansas Craigslist Free Stuff
Vanadium Conan Exiles
Hallowed Sepulchre Instances &amp; More
Draconic Treatise On Mining
Florida (FL) Powerball - Winning Numbers & Results
The Weather Channel Facebook
Washington Poe en Tilly Bradshaw 1 - Brandoffer, M.W. Craven | 9789024594917 | Boeken | bol
People Portal Loma Linda
Samantha Lyne Wikipedia
Highland Park, Los Angeles, Neighborhood Guide
Uky Linkblue Login
Elemental Showtimes Near Cinemark Flint West 14
Northeastern Nupath
Www Craigslist Milwaukee Wi
Conan Exiles: Nahrung und Trinken finden und herstellen
Hdmovie 2
Acts 16 Nkjv
Timeforce Choctaw
Free Personals Like Craigslist Nh
Mtr-18W120S150-Ul
Okc Body Rub
Myql Loan Login
Gs Dental Associates
A Christmas Horse - Alison Senxation
Table To Formula Calculator
Co10 Unr
Best Restaurants Ventnor
Kattis-Solutions
Craigslist Free Puppy
Fridley Tsa Precheck
Ultra Clear Epoxy Instructions
Craigslist Greencastle
Bimar Produkte Test & Vergleich 09/2024 » GUT bis SEHR GUT
Mydocbill.com/Mr
Midsouthshooters Supply
Felix Mallard Lpsg
Riverton Wyoming Craigslist
Weather Underground Corvallis
Ferguson Showroom West Chester Pa
Courses In Touch
Ehome America Coupon Code
Woody Folsom Overflow Inventory
Christie Ileto Wedding
Zadruga Elita 7 Live - Zadruga Elita 8 Uživo HD Emitirani Sat Putem Interneta
Research Tome Neltharus
Call2Recycle Sites At The Home Depot
Kidcheck Login
Códigos SWIFT/BIC para bancos de USA
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 5755

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.