1

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.

CaptainFreedom
  • 117
  • 4
  • 11
  • Possible duplicate of [How do I sum the values in an array of maps in jq?](https://stackoverflow.com/questions/28484534/how-do-i-sum-the-values-in-an-array-of-maps-in-jq) – TobiSH Feb 28 '18 at 12:27

2 Answers2

3

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 ))
peak
  • 105,803
  • 17
  • 152
  • 177
2

jq solution:

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

The output:

{
  "groupId1": 5,
  "groupId2": 4
}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105