How do I sum the values in an array of maps in jq?

前端 未结 3 1476
不思量自难忘°
不思量自难忘° 2020-12-08 14:50

Given a JSON stream of the following form:

{ \"a\": 10, \"b\": 11 } { \"a\": 20, \"b\": 21 } { \"a\": 30, \"b\": 31 }

I would like to sum t

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 15:08

    Another approach, which illustrates the power of jq quite nicely, is to use a filter named "sum" defined as follows:

    def sum(f): reduce .[] as $row (0; . + ($row|f) );
    

    To solve the particular problem at hand, one could then use the -s (--slurp) option as mentioned above, together with the expression:

    {"a": sum(.a), "b": sum(.b) }  # (2)
    

    The expression labeled (2) only computes the two specified sums, but it is easy to generalize, e.g. as follows:

    # Produce an object with the same keys as the first object in the 
    # input array, but with values equal to the sum of the corresponding
    # values in all the objects.
    def sumByKey:
      . as $in
      | reduce (.[0] | keys)[] as $key
        ( {}; . + {($key): ($in | sum(.[$key]))})
    ;
    

提交回复
热议问题