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.