if else
An if statement evaluates a conditional expression and returns the value under the if only if the conditional expression returns true. Otherwise, it returns the expression under else. Every if expression must have a matching else expression.
If/else expressions allow you to make decisions using logical operators and branch as a result.
operators and branch as a result.
if (<criteria_expression>) <return_if_true> else <return_if_false>
There are cases in DW where parentheses are optional, but it’s important to note the criteria must be surrounded by parentheses in if/else expressions.
The following example uses the input { country : “India” }, which is defined by the myVar variable in the header:
DataWeave Script:
%dw 2.0 var myVar = { country : "India" } output application/json --- if (myVar.country == "UAE") { currency: "EUR" } else { currency: "RUPEES" }
Output:
{ "currency": "RUPEES" }
You can use the if-else construct on any condition that evaluates to true or false, including mathematical, logical, equality, and relational statements. The condition can act on any valid input.
A mapping in ex4 that iterates over firstInput
The if else statement returns the value of the bookId as a Number if the value is equal to 101. It returns the specified string if the value is not equal to 101.
DataWeave Script:
%dw 2.0 var aRecord = [ "bookId":"101", "title":"world history", "price":"19.99" ] output application/xml --- { examples: { ex1 : if (1 + 1 == 55) true else false, ex2 : if ([1,2,3,4][1] == 1) 1 else "value of index 1 is not 1", ex3 : if (isEmpty(aRecord.bookId)) "ID is empty" else "ID is not empty", ex4 : aRecord.bookId map (idValue) -> if (idValue as Number == 101) idValue as Number else "not 101" } }
Output:
<?xml version='1.0' encoding='UTF-8'?> <examples> <ex1>false</ex1> <ex2>value of index 1 is not 1</ex2> <ex3>ID is not empty</ex3> <ex4>101</ex4> </examples> Follow Me If you like my post please follow me to read my latest post on programming and technology. Instagram Facebook
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…