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

前端 未结 3 1479
不思量自难忘°
不思量自难忘° 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:24

    Unless your jq has inputs, you will have to slurp the objects up using the -s flag. Then you'll have to do a fair amount of manipulation:

    1. Each of the objects needs to be mapped out to key/value pairs
    2. Flatten the pairs to a single array
    3. Group up the pairs by key
    4. Map out each group accumulating the values to a single key/value pair
    5. Map the pairs back to an object
    map(to_entries)
        | add
        | group_by(.key)
        | map({
              key: .[0].key,
              value: map(.value) | add
          })
        | from_entries
    

    With jq 1.5, this could be greatly improved: You can do away with slurping and just read the inputs directly.

    $ jq -n '
    reduce (inputs | to_entries[]) as {$key,$value} ({}; .[$key] += $value)
    ' input.json
    

    Since we're simply accumulating all the values in each of the objects, it'll be easier to just run through the key/value pairs of all the inputs, and add them all up.

提交回复
热议问题