軌道
/
jq
jq
/
課程大綱
/
條件式
條件

條件式 在 jq

7 個練習

關於 條件式

if 運算式

jq的條件運算式是if A then B else C end。

if-then-else就像所有jq內建函式一樣,是個篩選器:它接收輸入並產生輸出。

如果運算式A產生「真值」,if篩選器就會求值B。 否則會求值C。 if篩選器的輸入會傳遞給B或C。

42 | if . < 50 then "small" else "big" end      # => "small"
5 | if . % 2 == 0 then . / 2 else . * 4 end     # => 20
Note

else子句是選用的;下面兩個敘述是等價的。

if A then B else . end
if A then B end

巢狀 if 敘述

可以用elif加上更多條件。

42 | if . < 33 then "small"
     elif . < 66 then "medium"
     else "big"
     end
# => "medium"

需要多少elif子句就用多少。

真值

jq中唯一的「假」值是:false和null。 其他一切都是「真」,連數字零、空字串、空陣列和空物件也是。

布林運算子

布林運算子and和or可以用來建立複雜的查詢。

42 | if . < 33 or . > 66 then "big or small"
     else "medium"
     end

要取反,請用not。它是篩選器,不是運算子。

42 | if (. < 33 or . > 66 | not) then "medium"
     else "big or small"
     end

替代運算子

替代運算子讓你能在運算式為假或 null 時指定「預設」值。

A // B

# This is identical to
if A then A else B end

舉例來說

[3, 5, 18] | add / 2       # => 13
[]         | add / 2       # => error: null (null) and number (2) cannot be divided
[]         | add // 0 / 2  # => 0

還有更多嗎?

來自其他程式語言的程式設計師,可能會期待更多種類的條件指令,例如cond、case、switch、when、unless、三元運算子等等。 上面列出的運算子就是jq提供的全部。

透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 條件式

練習已鎖定

再解鎖 6 個練習,就能練習 條件式