【问题标题】:jq: count nest object values based on group byjq:根据分组计算嵌套对象值
【发布时间】:2018-12-13 19:38:19
【问题描述】:

json:

    [
  {
  "account": "1",
  "cost": [
      {
         "usage":"low",
         "totalcost": "2.01"
      }
   ]
  },
  {
  "account": "2",
  "cost": [
      {
         "usage":"low",
         "totalcost": "2.25"
      }
   ]
  },
  {
  "account": "1",
  "cost": [
      {
         "usage":"low",
         "totalcost": "15"
      }
   ]
  },
  {
  "anotheraccount": "a",
  "cost": [
      {
         "usage":"low",
         "totalcost": "2"
      }
   ]
  }
]

预期结果:

account cost
1       17.01
2       2.25
anotheraccount cost
a              2

我能够提取数据,但不知道如何聚合它。

jq '.[] | {account,cost : .cost[].totalcost}'

有没有办法在使用 jq 时做到这一点,所以我可以得到所有类型的帐户和与之相关的费用?

【问题讨论】:

    标签: json jq


    【解决方案1】:

    两个辅助函数将帮助您到达目的地:

    def sigma( f ): reduce .[] as $o (null; . + ($o | f )) ;
    
    def group( keyname ):
      map(select(has(keyname)))
      | group_by( .[keyname] )
      | map({(keyname) : .[0][keyname], 
              cost: sigma(.cost[].totalcost | tonumber) })
    ;
    

    使用这些,以下调用:

    group("account"),
    group("anotheraccount")
    

    产量:

    [{"account":"1","cost":17.009999999999998},{"account":"2","cost":2.25}]
    [{"anotheraccount":"a","cost":2}]
    

    您应该能够在 jq 中管理最后的格式化步骤。

    【讨论】:

    • 我在命令行中尝试了这个,我怎么能在上面运行?抱歉,刚接触此内容,不了解如何使上述代码正常工作?
    • 我建议使用 -f 命令行选项。请参阅 jq 文档。
    • 以上代码是用python写的吗?我在 python 中尝试过,第一行 def sigma 出现错误,因为语法无效?
    • 或者是否有在 bash 中使用管道的单线解决方案? jq '.[] | 中的一些东西{account,cost : .cost[].totalcost}'
    • 您要求 jq 解决方案,这是我提供的。 (我之前说过,请查阅jq文档。)
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2021-10-10
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多