【问题标题】:Group and count JSON using jq [duplicate]使用 jq 对 JSON 进行分组和计数 [重复]
【发布时间】:2021-03-15 16:24:05
【问题描述】:

我正在尝试将以下 JSON 转换为具有每个唯一“名称”和总数(即该名称出现的次数)的 csv。

当前数据:

[
  {
    "name": "test"
  },
  {
    "name": "hello"
  },
  {
    "name": "hello"
  }
]

理想输出:

[
    {
        "name": "hello",
        "count": 2
    },
    {
        "name": "test",
        "count": 1
    }
]

我试过[.[] | group_by (.name)[] ],但得到以下错误:

jq: 错误 (at :11): 不能用字符串 "name" 索引字符串

JQ播放链接:https://jqplay.org/s/fWqNUii1b2

注意,我已经在使用 jq 将初始原始数据格式化为上述格式。 JQ播放链接请看这里:https://jqplay.org/s/PwwRYscmBK

【问题讨论】:

    标签: json group-by jq data-manipulation counting


    【解决方案1】:
    group_by(.name) 
        | map({name: .[0].name, count: length})   
    
    [
      {
        "name": "hello",
        "count": 2
      },
      {
        "name": "test",
        "count": 1
      }
    ]
    

    Jq▷Play


    基于 OP 的 comment,使用以下 jq 过滤器计算多个对象中的每个名称,其中 .name 是嵌套的。

    map(.labels) 
        | map({name: .[0].name, count: length})
    

    Jq▷Play

    【讨论】:

    • 谢谢,这似乎是孤立的。您如何将它与将原始数据格式化为所需初始格式的[.[] | {name: .labels[].name} ] 结合使用?
    • 请分享“初始格式”,以便我们使用它;)
    • 已添加,请参阅原帖底部的 jqplay 链接。
    • 您要计算每个对象中的名称吗?或者您是否正在寻找一种方法来计算每个分离对象的数量?
    • 完美运行,谢谢!
    【解决方案2】:
    echo '[{"name": "test"}, {"name": "hello"}, {"name": "hello"}]' | jq 'group_by (.name)[] | {name: .[0].name, count: length}' | jq -s
    
    [
      {
        "name": "hello",
        "count": 2
      },
      {
        "name": "test",
        "count": 1
      }
    ]
    

    【讨论】:

    • OP 需要数组中的这两个对象。
    • @0stone0 哦,你是对的!固定!
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 2021-06-26
    • 2018-11-27
    • 2017-05-31
    • 1970-01-01
    相关资源
    最近更新 更多