Product SiteDocumentation Site

Chapter 9. Control Flow Expressions

9.1. Conditional Expressions
9.2. Switch expressions
9.3. Try-Catch expressions
JSONiq supports control flow expressions such as conditional expressions (if then else), switch, and typeswitch. At least the first two should be familiar to any programmer.

9.1. Conditional Expressions

A conditional expression allows you to pick the one or the other value depending on a boolean value.
Example 9.1. A conditional expression.
if (1 + 1 eq 2)
then { "foo" : "yes" }
else { "foo" : "false" }
Results:
{
  "foo" : "yes"
}

The behavior of the expression inside the if is similar to that of logical operations (two-valued logics), meaning that non-boolean values get converted to a boolean. The exists() builtin function can be useful to know if a sequence is empty or not.
Example 9.2. A conditional expression.
if (null) then { "foo" : "yes" }
          else { "foo" : "no" },
if (1) then { "foo" : "yes" }
       else { "foo" : "no" },
if (0) then { "foo" : "yes" }
       else { "foo" : "no" },
if ("foo") then { "foo" : "yes" }
           else { "foo" : "no" },
if ("") then { "foo" : "yes" }
        else { "foo" : "no" },
if (()) then { "foo" : "yes" }
        else { "foo" : "no" },
if (exists(collection("faqs"))) then { "foo" : "yes" }
                               else { "foo" : "no" }
Results:
{
  "foo" : "no"
}
{
  "foo" : "yes"
}
{
  "foo" : "no"
}
{
  "foo" : "yes"
}
{
  "foo" : "no"
}
{
  "foo" : "no"
}
{
  "foo" : "yes"
}

Note that the else clause is mandatory (but can be the empty sequence)
Example 9.3. A conditional expression.
if (1+1 eq 2) then { "foo" : "yes" } else ()
Results:
{
  "foo" : "yes"
}