jq: count nest object values based on group by

后端 未结 1 429
星月不相逢
星月不相逢 2021-01-16 07:11

Json:

    [
  {
  \"account\": \"1\",
  \"cost\": [
      {
         \"usage\":\"low\",
         \"totalcost\": \"2.01\"
      }
   ]
  },
  {
  \"account\":         


        
1条回答
  •  伪装坚强ぢ
    2021-01-16 07:23

    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) })
    ;
    

    With these, the following invocations:

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

    yield:

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

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

    0 讨论(0)
提交回复
热议问题