Reputation: 11
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?
Upvotes: 1
Views: 1220
Reputation: 36033
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
Upvotes: 3