⇠ back to TILs

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

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 .nonexistant
null

Instead, you can use the jq's has function to determine the difference:

echo $json | jq 'has("test")'
trueecho $json | jq 'has("nonexistant")'
false

Thoughts? Corrections? Feel free to reply via email!