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

Use jq to count elements based on group by

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?

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

>Solution :

Yes, it is.

  1. Extract all genres into array
  2. Group genres
  3. Map to a key-value pair (key = any element of the group, we’ll take the first; value = count of elements in the group)
  4. Build object from key-value pairs
map(.genres[].tag)
| group_by(.)
| map({ key:first, value:length })
| from_entries

Output:

{
  "Drama": 1,
  "History": 1,
  "Horror": 1,
  "Mystery": 1,
  "Thriller": 2,
  "War": 1
}

Alternatively, use a reduce based approach and simply increase a counter:

reduce .[].genres[].tag as $genre ({}; .[$genre] += 1)

This is likely more efficient than building an array and grouping.

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