jq:根据分组依据对嵌套对象值进行计数 [英] jq: count nest object values based on group by

查看:59
本文介绍了jq:根据分组依据对嵌套对象值进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我能够提取数据,但不确定如何聚合.

I am able to pull out data but not sure how to aggregate it.

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

使用jq是否可以做到这一点,所以我可以获得与它们相关的所有类型的帐户和成本?

Is there a way to do this in using jq, so I get all types of accounts and costs associated with them?

推荐答案

两个帮助器功能将帮助您到达目的地:

Two helper functions will help you get you to your destination:

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中管理最后的格式化步骤.

You should be able to manage the final formating step in jq.

这篇关于jq:根据分组依据对嵌套对象值进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆