Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataWeave 2.0 If else condition

Tags:

dataweave

Am fairly new to Dataweave, trying to achieve simple if else condition based on below

if (vars.country == "USA")
  { currency: "USD" }
else { currency: "EUR" }

This works fine. However, when I am trying with other json variables as below, it fails

%dw 2.0
output application/json encoding="UTF-8"
---
Name: "ABC",
if (vars.country == "USA")
  { currency: "USD" }
else { currency: "EUR" }
like image 715
Ranjith Reddy Avatar asked Mar 12 '26 15:03

Ranjith Reddy


1 Answers

A few ways to get it done:

Using a similar expression to what you have, you must enclose objects in {} when having more than one field in them

%dw 2.0
output application/json encoding="UTF-8"
---
{
  Name: "ABC",
  (if (vars.country == "USA")
     currency: "USD" 
   else  
     currency: "EUR")
}

Using the ++ function, to concatenate objects, heres the documentation

%dw 2.0
output application/json encoding="UTF-8"
---
{Name: "ABC"} ++ (
    if (vars.country == "USA")
        {currency: "USD"}
    else
        {currency: "EUR"}
)

Finally, using the conditional elements feature

%dw 2.0
output application/json encoding="UTF-8"
---
{
    Name: "ABC",
    (currency: "USD") if (vars.country == "USA"),
    (currency: "EUR") if not (vars.country == "USA")
}

Pick the one you like.