Using JQ to filter the keys that have a boolean equal to true

I have this JSON file:

{
   "books":{
      "book-name-1":{
         "path":"management/business",
         "availability": true,
         "vars":{
            "author":"John",
            "year":"2005"
         }
      },
      "book-name-2":{
         "path":"engineering/computing",
         "availability": false,
         "vars":{
            "author":"Rick",
            "year":"2010"
         }
      },
      "book-name-3":{
         "path":"finance/general",
         "vars":{
            "author":"Joe",
            "year":"2020"
         }
      },
      "book-name-4":{
         "path":"medicine/general",
         "availability": true,
         "vars":{
            "author":"Stacy",
            "year":"2018"
         }
      }
   }
}

and I can't manage to filter it in such a way that I can get the names of the books that "availability" is equal to true.

Note for example that book-name-3 does not have that variable and book-name-2 has it set to false.

So, the output I expect to get after filtering is:

book-name-1,
book-name-4

How could I make it possible using jq?

1 answer

  • answered 2022-05-06 21:51 pmf

    One way could be to reduce the items to those matching the criteria, and then output the key names:

    jq -r '.books | .[] |= select(.availability) | keys_unsorted[]'
    

    Demo

    Another one could be using to_entries and work with .key and .value:

    jq -r '.books | to_entries[] | select(.value.availability).key'
    

    Demo

    Output in both cases:

    book-name-1
    book-name-4
    

    To also feature the commas, you could leave it as array, and use a join(",\n") to combine:

    book-name-1,
    book-name-4
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum