如何在jq中的地图数组中求和? [英] How do I sum the values in an array of maps in jq?
问题描述
给出以下格式的JSON流:
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 the values in each of the objects and output a single object, namely:
{ "a": 60, "b": 63 }
我猜想这可能需要将上面的对象列表展平为[name, value]
对的数组,然后使用reduce
对值求和,但是使用reduce
的语法文档非常糟糕. /p>
I'm guessing this will probably require flattening the above list of objects into a an array of [name, value]
pairs and then summing the values using reduce
but the documentation of the syntax for using reduce
is woeful.
推荐答案
除非您的jq具有inputs
,否则您将不得不使用-s
标志将对象吸干.然后,您必须进行大量的操作:
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:
- 每个对象都需要映射到键/值对
- 将线对平整为单个阵列
- 通过密钥将配对分组
- 将累积值的每个组映射到单个键/值对
- 将对映射回对象
map(to_entries)
| add
| group_by(.key)
| map({
key: .[0].key,
value: map(.value) | add
})
| from_entries
使用jq 1.5可以大大改善这一点:您可以消除拖尾的感觉,而直接阅读inputs
.
$ 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.
这篇关于如何在jq中的地图数组中求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!