Given a JSON stream of the following form:

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

我想将每个对象中的值相加,并输出一个对象,即:

{ "a": 60, "b": 63 }

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.

推荐答案

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. 将对展平为单个数组
  3. 按键分组
  4. 将每个组的值累加到一个键/值对上
  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.

Json相关问答推荐

服务器不返回JSON

如何使用Aeson解码带有Unicode字符的JSON文件?

Flutter -控制器问题-JSON API

在MongoDB中检索某个月份和年份的JSON文档

用 Jolt 替换 JSON 中的值

Moshi:序列化 List 时出现问题

NiFi 使用嵌套数组将 avro 转换为 JSON 数组格式

从字节解码 JSON 数据,将 float 值更改为 int

使用带有逗号的字段名称构建 struct

Vue 3如何将参数作为json发送到axios get

下一个 Js 部署在 getStaticPath 函数上失败:在 JSON.parse 的位置 0 的 JSON 中出现意外的令牌 < 但在本地运行

如何从 rails 中的 respond_to 方法生成 json?

从 JSON 对象中删除键值对

JBuilder中未定义的局部变量或方法json

如何在不解析的情况下在javascript中同步包含JSON数据?

规范化 JSON 文件

在 Webpack 中加载静态 JSON 文件

使用 Python 3 读取 JSON 文件

Swift :将 struct 转换为 JSON?

与classic 规范化表相比,postgres JSON 索引是否足够高效?