2

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" }
Ranjith Reddy
  • 129
  • 1
  • 3
  • 12

2 Answers2

9

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.

George
  • 2,758
  • 12
  • 16
4

You need to surround the condition in parenthesis like this

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

Output

{
  "Name": "ABC",
  "currency": "EUR"
}