分支

分支语句 属于 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”值:false和null。 其他一切都是“true”,甚至包括数字零、空字符串、空数组和空对象。

布尔运算符

布尔运算符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

替代运算符

替代运算符允许你指定一个“默认”值,当表达式为 false 或 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 个练习即可练习 分支语句