Conditional structures: Difference between revisions

(jq)
Line 1,834:
# all JSON values are truthy except for false and null;
# if cond evaluates to nothing (i.e., produces an empty stream), then the entire if-then-else-end expression also produces an empty stream.
 
The general pattern allows one or more "elif _ then _" clauses:
<lang jq>
if cond then f elif cond1 then f1 .... else g end
</lang>
 
For example:<lang jq>
Line 1,842 ⟶ 1,847:
</lang>Notice that if cond produces a nonempty stream, then the entire expression will typically do the same. Since f and g also can produce streams, this lends itself to interesting Cartesian-product possibilities.
 
There is no "case <exp>" construct, but the idiom illustrated by the following example can be used to avoid the need to create a temporary variable to hold the "case" expression:<lang jq>
exp
| if . == true then "true"
elif . == false then "false"
elif . == null then "maybe"
elif type == "string" then .
else error("unexpected value: \(.)")
end</lang>
Since jq's <tt>and</tt> and <tt>or</tt> are short-circuiting, they can also be used for branching.
 
2,502

edits