I have a list of movies like this:
[
{
"title":"X",
"genres":[
{
"tag":"Horror"
},
{
"tag":"Thriller"
},
{
"tag":"Mystery"
}
]
},
{
"title":"Zero Dark Thirty",
"genres":[
{
"tag":"Thriller"
},
{
"tag":"Drama"
},
{
"tag":"History"
},
{
"tag":"War"
}
]
}
]
I want to query all unique genres and count the number of movies, where the output looks like this:
{
"Horror":1,
"Thriller":2,
"Mystery":1,
"Drama":1,
"History":1,
"War":1
}
Is this possible with jq
?
2
Answers
Yes, it is.
Output:
Alternatively, use a
reduce
based approach and simply increase a counter:This is likely more efficient than building an array and grouping.
There is a generic "bag of words" function that makes it easy to solve this task efficiently:
With this arrow in your quiver, there are many ways to solve the specific problem at hand. Here’s one that assumes all .tag values are relevant: