问题描述
给定以下格式的 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
的语法文档很糟糕.
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
标志 slurp 对象.然后你必须做大量的操作:
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,这可以大大改善:您可以取消 slurping,直接读取 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 中的地图数组中的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!