Variables In Dataweave

 

There are different way of declaring and using the variables in dataweave.

  • Global variables are initialized in the header of the DataWeave script and can be referenced by name from anywhere in the body of a DataWeave script.
  • The header of a DataWeave script accepts a var directive that initializes a variable, for example: var string=’USA’. You can declare multiple global variables on separate lines in the header.
  • Local variables are initialized in the body of the DW script and can be referenced by name only from within the scope of the expression where they are initialized.

Note: DW variables cannot be reassigned. They are also distinct from variables that are part of the Mule message (such as target variables). variables do not persist beyond the scope of the script in which they are initialized

Input:

{
  "id": "1",
  "employee_name": "John",
  "employee_salary": 320800,
  "employee_age": 61,
  "profile_image": ""
}

Global Dataweave Variable:

Dataweave Expression:

%dw 2.0
output application/json
var value = "Welcome"
---
{
  message: value ++ vars.name
}

Output:

{
  "message": "WelcomeJohn"
}

Local Dataweave Variable:

Dataweave Expression:

%dw 2.0
output application/json
---
{
  message: using(value = "Hello") value ++ payload.employee_name
}

Output:

{
  "message": "HelloJohn"
}
  
Thank you for taking out time to read the above post. Hope you found it useful. In case of any questions, feel free to comment below. Also, if you are keen on knowing about a specific topic, happy to explore your recommendations as well.
 
For any latest updates or posts on our website, you can follow us on LinkedIn. Look forward to connecting with you there.


Share this:
Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Naveen
Naveen
3 years ago

thanks

Shabeer
Shabeer
1 year ago

Thank you

R Palani
R Palani
6 months ago

%dw 2.0
output application/json
var value = “Welcome”

{
message: value ++ payload.employee_name
}