Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter a key using jq in bash

I have the following JSON:

{
  "a_key": "A",
  "key_to_filter": "B",
  "c_key": "C"
}

I want to get all the keys using jq as a compressed response (using jq -c "keys").

How can I get all the keys of this JSON without the key "key_to_filter"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In other words, I need ["a_key", "c_key"]

>Solution :

You could just subtract that one from the array of keys:

jq -c 'keys - ["key_to_filter"]'

Demo

More verbosely but also more efficiently (if it matters), you could use a map to select what you want:

jq -c 'keys | map(select(. != "key_to_filter"))'

Demo

As @artild pointed out in a comment, you could also first delete the item in question, and just then get all keys:

jq -c 'del(.key_to_filter) | keys'

Demo

Output:

["a_key","c_key"]

Note that keys returns a sorted array. If you want them unsorted, use keys_unsorted instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading