Dataweave 1.0 in Mule | Variables | Functions | Data Types




Dataweave 1.0 in Mule

Defining variable in dataweave : 

%dw 1.0
%var rate=5
%output application/json
---
{
variable value : rate
currency: payload.price * rate
}

Defining function in dataweave : 

%dw 1.0
%output application/json
%function name(user){firstName: payload.name}
---
{
 user: name(payload)
}

Data types in mule : 

Simple values can be of the following types:

String : Double quoted ("Hello") or Single quoted ('Hello')

Boolean : Literals true or false

Number : Decimal and Integer values are supported (ex: 2.0)

Date : IS0-8601 enclosed by "|" (ex:|2003-10-01T23:57:59Z|)

Regex : Regex expression enclosed by "/" (ex:/(\d+)-(\d+)/)


Adding data to an existing input payload : 

input : 

{
"id" : 1
}

%dw 1.0
%output application/json

---
{
"id" : payload.id + 3
}


Flow Control Expressions :

1)When Otherwise

The keyword when conditionally evaluates a part of your DataWeave code, depending on if an expression evaluates to true or to false. You can make a single line conditional, or enclose a whole section in curly brackets. In case the when expression evaluates to false, its corresponding part of the code is ignored, and the code that corresponds to the otherwise expression is executed.

%dw 1.0
%output application/json

---
{
"id" : payload when payload.id > 2 otherwise null
}

2) Unless Otherwise

The keyword unless conditionally evaluates a part of your DataWeave code, depending on if an expression evaluates to true or to false. You can make a single line conditional, or enclose a whole section in curly brackets. In case the unless expression evaluates to true, its corresponding part of the code is ignored, and the code that corresponds to the otherwise expression is executed.

%dw 1.0
%output application/json

---
{
"id" : payload unless payload.id > 2 otherwise null
}

3) Default

Assigns a default value in case no value is found in the input field.

%dw 1.0
%output application/json

---
{
"id" : payload.id default 2
}

Matching Patterns in Mule 

1) Expression Pattern

Matches when running a certain expression over the evaluated value returns true.

Transform
%dw 1.0
%output application/json
---
{
  a: payload.string match {
    str when str == "Mariano" -> str ++ " de Achaval",
    str when str == "Emiliano" -> str ++ " Lesende"
  },
  b: payload.number match {
    n when n < 3 -> "lower",
    n when n > 3 -> "higher"
  }
}

Input: JSON
Input
{
  "string": "Emiliano",
  "number": 3.14
}
Output: JSON
Output
{
  "a": "Emiliano Lesende",
  "b": "higher"
}

2) Match Type
Matches when the evaluated value is of the specified type

Transform
%dw 1.0
%output application/json
---
{
  a: payload.a match {
    :object -> "OBJECT",
    :string -> "STRING",
    :number -> "NUMBER",
    :boolean -> "BOOLEAN",
    :array -> "ARRAY",
    :null -> "NULL"
  },
  b: payload.b match {
    y is :object -> { type: "OBJECT", y: y },
    y is :string -> { type: "STRING", y: y },
    y is :number -> { type: "NUMBER", y: y },
    y is :boolean -> { type: "BOOLEAN", y: y },
    y is :array -> { type: "ARRAY", y: y },
    y is :null -> { type: "NULL", y: y }
  }
}
Input: JSON
Input
{
  "a": "Emiliano",
  "b": 3.14
}
Output: JSON
Output
{
  "a": "STRING",
  "b": {
    "type": "NUMBER",
    "y": 3.14
  }
}

3) Match Regex
Matches when the evaluated value fits a given regular expression

Transform
%dw 1.0
%output application/json
---
{
  a: payload.phones map ($ match {
     /\+(\d+)\s\((\d+)\)\s(\d+\-\d+)/ -> { country: $[0], area: $[1], number: $[2] },
     /\((\d+)\)\s(\d+\-\d+)/ -> { area: $[1], number: $[2] }
   }),
 b: payload.phones map ($ match {
   phone: /\+(\d+)\s\((\d+)\)\s(\d+\-\d+)/ -> { country: phone[0], area: phone[1], number: phone[2] },
   phone: /\((\d+)\)\s(\d+\-\d+)/ -> { area: phone[1], number: phone[2] }
 })
}
Input: JSON
Input
{
  "phones": [
    "+1 (415) 229-2009",
    "(647) 456-7008"
  ]
}
Output: JSON
Output
{
  "a": [
    {
      "country": "+1 (415) 229-2009",
      "area": "1",
      "number": "415"
    },
    {
      "area": "647",
      "number": "456-7008"
    }
  ],
  "b": [
    {
      "country": "+1 (415) 229-2009",
      "area": "1",
      "number": "415"
    },
    {
      "area": "647",
      "number": "456-7008"
    }
  ]
}

System Values in Mule

1) Now
Returns the present moment in (:datetime) type.

Transform
%dw 1.0
%output application/json
---
{
  a: now,
  b: now.day,
  c: now.minutes
}

2) Random
Returns a random number of type (:number) between 0 and 1

Transform
%dw 1.0
%output application/json
---
{
  price: random * 1000
}


3) Log
(prefix :string,value :any)
Returns the specified value and also logs the value in the DataWeave representation with the specified prefix.

Transform
%dw 1.0
%output application/json
---
{
  result: log("Logging the array",[1,2,3,4])
}
Output
{
  "result": [1,2,3,4]
}
Logger output :

Logging the array [1,2,3,4]


© 2020 goformule.com

Share on :

Mule 4:

XML to JSON in mule 4 Web service consumer VM Validation in Mule 4 Until Successful
Sub flow Set Variable & Remove Variable Set Transaction ID Scatter Gather Round Robin
Consume Restful Service CRUD in Mule 4 Parse Template Object to JSON Load Static Resource
JSON to XML Invoke Idempotent Filter ForEach Flat file to JSON
Fixwidth to JSON First Successful File Execute Error Handling
Email Dynamic Evaluate Custom Business Event CSV to JSON Copybook to JSON
Choice Router Async RabbitMQ


Mule 3:


Database Connector Async CXF Attachement XSLT
Mongo DB Cache scope Custom Business Event Gzip Compress Expression
SMTP For Each Expression Javascript Filter Reference
Salesforce Message Enricher Groovy Parse Template Idempotent
VM Poll Invoke Ruby Message
Webservice consumer Python Transformer reference Message Property Not
Collection Aggregator First Sucessful Catch Exception Strategy Reference Exception Strategy Or
Choice Message Chunk Aggregator Choice Exception Strategy Global Exception Strategy Schema Validation
Custom Aggregator Scatter Gather Custom Exception Strategy Batch Processing MEL
M Unit RAML Map Operator API Mocking Dataweave


Converter Tools :

JSON to XML Converter XML to JSON Converter Decimal to Binary Decimal to Octal Binary to Decimal
Binary to Hexadecimal Binary to Octal Hexadecimal to Decimal Hexadecimal to Binary Hexadecimal to Octal
Octal to Decimal Octal to Binary Octal to Hexadecimal Number to Words Converter Text to Hex Converter
Hex to Text String to Binary Converter Binary to String Converter Word to HTML Converter Word to PDF Converter
JSON to YAML Converter CSV to JSON Converter XML to XSLT Converter XML to YAML Converter
JSON to CSV Converter JSON to TSV Converter CSV to TSV Converter CSV to XLS Converter


Image Tools :

PNG to JPG Converter PNG to BMP Converter PNG to GIF Converter JPG to PNG Converter JPG to BMP Converter
JPG to GIF Converter GIF to PNG Converter GIF to JPG Converter GIF to BMP Converter PNG to PDF Converter
JPEG to PDF Converter JPG to PDF Converter BMP to PDF Converter GIF to PDF Converter


String Utilities :

Reverse String Random String Generator Base64 Encoder Base64 Decoder Words Counter
Remove Accents Remove Duplicate Lines Remove Empty Lines Remove Line Breaks Remove Similar Lines
Sort Text Lines Reverse Text Lines Random Words Generator


Number Utilities :

Square Root Calculator Random Number Generator Area of Circle Calculator Date Calculator


Other Tools :

Find IP of Website Password Generator URL Encoder URL Decoder lorem ipsum Generator
IP to Hostname Port Checker JSON Escape JSON Unescape


Free Rest APIs for Testing :

GET Sample Rest APIs POST Sample Rest API PUT Sample Rest API PATCH Sample Rest API DELETE Sample Rest API
Login Sample Rest API User Registration Sample API User Registration Unsuccessful Sample Rest API Delay Response