Play with brackets () {} []

and Complex If-else conditions

It’s very important to understand the bracket available in Dataweave and how smartly we can use to yield different results based on their usage. Over here we play with brackets like () {} and [] to see them in action. Also we will look into significance in complex if-else conditions.

How is an Object represented in DataWeave?

Objects are represented in key-value pair inside a curly brace { }.

Example :

{
    "fName": "Max",
    "lName": "Mule"
}

How is an Array represented in DataWeave?

Arrays are represented in square brackets [] that contains String, Numbers or Objects

Example

An Array of Person Objects:

"persons": [{
    "fName": "Max",
    "lName": "Mule"
},
{
    "fName": "John",
    "lName": "Paul"
}]

An Array of Strings

"name":["Max", "John"]

How to use Round Brackets or parentheses ( ) in DataWeave.

Round Brackets/Parentheses/Open-Closed Brackets are trickier to use among other two backets. Parentheses are used to

  • Evaluate an expression ( Known as evaluation paratheses)
  • Pass arguments to functions

Use cases of Evaluation Paratheses :

Using () to explode or encapsulate array in object.

Example 1 :

%dw 2.0
output application/dw

var num = [{
    a: 1,
    b: 2,
    c: 3
},
{
    d: 4,
    e: 5
}]
---
{
    (num) evaluate expression
}

Output:

{
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5
}

Explanation: An array of Object “num” is declared in DW header. In the body, num is evaluated by () brackets and returns the result by encapsulating array in one object.

Example 2:

%dw 2.0
output application/dw
var place = {
    "country":"India",
    "cities":[{
        "city1":"Delhi"
        },
        {
        "city2":"Mumbai"
        },
        {
        "city3":"Bangalore"
        }]
    }
---
{
    "country": place.country,
    (place.cities) evaluate expression
}

Output :

{
    country: "India",
    city1: "Delhi",
    city2: "Mumbai",
    city3: "Bangalore"
}

Explanation: An Object of “place” is declared in DW header. This object has an array of cities.

In the body, place is transformed by country and its cities in single Object thus cities are evaluated by () brackets and returns flatten object. Using () to explode array of object is like using Map function. Below will return the same response.

{
    "country": place.country,
    (place.cities map (item, index) -> {(item)})
}

Use evaluation expression and if-else condition to show specific data items.

Example :

%dw 2.0
output application/json
var flights = [
    { "toAirport": "SFO", "price": 550, "airline": "American" },
    { "toAirport": "MUA", "price": 200, "airline": "Flamingo" },
    { "toAirport": "NY", "price": 300, "airline": "American" },
    { "toAirport": "NY", "price": 600, "airline": "Dallas" }
]
---
"flights" : flights map ((item, index) ->       //Passing param
    (                                           //1.Evaluation
        if(item.toAirport=="NY")
        {
            "airline" : item.airline,
            "destination": item.toAirport
        } else ({})
    )
)-- ([{}])                                      //2.Evaluation

Output:

{
    "flights": [{
            "airline": "American",
            "destination": "NY"
        },
        {
            "airline": "Dallas",
            "destination": "NY"
        }
    ]
}

Explanation : An array of object “flights” is declared. The required output should only have those flights which has destination as NY.

Other than passing param paratheses which is used in map func(),1st

evaluation paratheses evaluates if-else condition operator and returns the result based on the expression passed to it.

2nd evaluation paratheses evaluates to remove empty object.

 

Use evaluation expression and if-else condition to show or hide key/value in Output.

Example :

%dw 2.0
output application/json
var employee =[{
    "fName" : "Max",
    "lName" : "Mule",
    "dep" : "Opertions"
},
{
    "fName" : "John",
    "lName" : "Clen",
    "dep" : "Marketing"
}]
---
employee map ( //1.Evaluation
    (item, index) -> {
        "name" : item.fName ++" "++ item.lName,
        (      //2.Evaluation
            if(item.dep == "Marketing")
                "department" : item.dep
            else null
        )
    }
)

Output:

[
	{
		"name": "Max Mule"
	},
	{
		"name": "John Clen",
		"department": "Marketing"
	}
]

Explanation : An array of object “employee” is declared. In the output, show “department” only if it is “Marketing”.

1stevaluation paratheses evaluates map function and returns an Array.

2nd evaluation paratheses evaluates the if-else condition and creates the “department data field, only if department is equals to “Marketing

 


Post Submitted by:

Atul Verma
MuleSoft Integration Architect at Accenture
LinkedIn Profile
  
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
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mariano de achaval
Mariano de achaval
1 month ago

This blog is excellent though for conditional fields there is a simpler sintax is { n:1, (a: true) if(vars.a ==1)} this exampñe will add the field a when vars.a is 1