'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?
Solution 1:[1]
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[]'
Another one could be using to_entries and work with .key and .value:
jq -r '.books | to_entries[] | select(.value.availability).key'
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pmf |
