PedroTroller
PedroTroller

Reputation: 48

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

If I execute

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

I receive null as result.

But if I execute

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

I also receive null as result.

In the first case, the value is null, in the second it does not exist (can't be resolved). Is there any way to tell the two cases apart?

Upvotes: 0

Views: 239

Answers (1)

oguz ismail
oguz ismail

Reputation: 50750

Yes, there is. The has built-in returns a boolean value representing whether its argument exists in its input as a key (or index, if the input is an array).

$ 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

Upvotes: 3

Related Questions