Aggregate five individual objects to desired output using jq

Viewed 78

Iwas able to transform data but not getting the desired output

filter (which i tried):

[inputs | {author , totalpages : .pages , books : [{"title": .title, "year" : .year }] } ] | sort

Input :

{"title":"War of the worlds","author":"H G Wells","year":1896,"pages":203}
{"title":"The invisible man","author":"H G Wells","year":1895,"pages":2136}
{"title":"The Lost World","author":"A C Doyle","year":1912,"pages":185}
{"title":"A Study in Scarlet","author":"A C Doyle","year":1887,"pages":251}
{"title":"20,000 leagues under the sea","author":"J Verne","year":1870,"pages":450}

output should be:

{
  "author": "A C Doyle",
  "totalpages": 436,
  "books": [
    {
      "title": "The Lost World",
      "year": 1912
    },
    {
      "title": "A Study in Scarlet",
      "year": 1887
    }
  ]
}
{
  "author": "H G Wells",
  "totalpages": 2339,
  "books": [
    {
      "title": "War of the worlds",
      "year": 1896
    },
    {
      "title": "The invisible man",
      "year": 1895
    }
  ]
}
{
  "author": "J Verne",
  "totalpages": 450,
  "books": [
    {
      "title": "20,000 leagues under the sea",
      "year": 1870
    }
  ]
}
1 Answers

Just a series of transformation is all is required, starting with group_by()

jq -n '
[ inputs ] | 
group_by(.author) | 
map
( 
  { 
    author: .[0].author, 
    totalpages: ( map(.pages) | add ), 
    books: ( map( { title, year } ) ) 
  }
)'

jqplay - demo

Related