【问题标题】:Aggregate five individual objects to desired output using jq使用 jq 将五个单独的对象聚合到所需的输出
【发布时间】:2020-12-26 08:16:49
【问题描述】:

我能够转换数据但没有得到想要的输出

过滤器(我试过):

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

输入:

{"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}

输出应该是:

{
  "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
    }
  ]
}

【问题讨论】:

    标签: json group-by aggregate jq


    【解决方案1】:

    只需一系列转换即可,从group_by()开始

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

    jqplay - demo

    【讨论】:

    • jq -n '[ inputs ] | ...'也可以写成jq -s '...'
    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 2017-06-29
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多