简体   繁体   中英

How group and sum items using jq?

I have following JSON:

{  
  "groupId1" : {
     "list" : [
       {
       "field1": "somevalue",
       "count": 2,
       "field3": "somevalue"
       },
       {
       "field1": "somevalue",
       "count": 3,
       "field3": "somevalue"
       }
     ]
   },
  "groupId2" : {
     "list" : [
       {
       "field1": "somevalue",
       "count": 0,
       "field3": "somevalue"
       },
       {
       "field1": "somevalue",
       "count": 4,
       "field3": "somevalue"
       }
     ]
   },     
 ...
}

And result i want to achieve(using jq) is:

[
  "groupId1":5,
  "groupId2":4
]

Each group has exactly one "list" element.

I understand that i shoud use group by and sum, but i can't get it work.

jq solution:

jq '. as $o | [ keys_unsorted[] 
                | {(.) : (reduce $o[.].list[] as $i (0; . + $i.count))} ] | add' file.json

The output:

{
  "groupId1": 5,
  "groupId2": 4
}

This is one of those cases where having the following definition in your ~/.jq or jq "standard library" really helps:

def sigma(stream): reduce stream as $x (null; . + $x );

With that, you can just write the very readable:

map_values( sigma(.list[] | .count ))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM