Use jq to see if a JSON key exists
I’m constantly using jq
to deal with JSON via the CLI.
Today I needed to figure out the difference between a key existing with a null
value or not existing at all in a bit of JSON.
By default, “querying” a key via jq
will return null
whether the key exists and is null
, or the key doesn’t exist:
△ # NOTE: the following is in fish, but should be straightforward to port to other shells
△ set json '{"test": null}'
△ echo $json | jq .test
null
△ echo $json | jq .nonexistent
null
Instead, you can use the jq
’s has
function to determine the difference:
△ echo $json | jq 'has("test")'
true
△ echo $json | jq 'has("nonexistent")'
false