有没有办法区分空值和缺少键?

Is there a way to differentiate between a null value and the absence of a key?

如果我执行

echo '{"foo": "bar", "baz": null}' | jq '.baz'

我收到 null 作为结果。

但是如果我执行

echo '{"foo": "bar", "baz": null}' | jq '.hello'

我也收到 null 作为结果。

在第一种情况下,值为null,在第二种情况下,它不存在(无法解析)。有什么办法可以区分这两种情况吗?

是的,有。 has built-in returns 一个布尔值,表示其参数是否作为键(或索引,如果输入是数组)存在于其输入中。

$ echo '{"foo": null}' | jq 'has("foo")'
true
$ echo '{"foo": null}' | jq 'has("bar")'
false
$ echo '[null]' | jq 'has(0)'
true
$ echo '[null]' | jq 'has(1)'
false