stream - 添加非数组格式的数字?或者如何过滤到数组以便我可以总结

标签 stream addition jq

在 jq 的早期版本中,我能够运行以下命令:

cat pull_requests.json | jq '.data.organization.repositories.nodes[] | .pullRequests.totalCount | add'

在此示例数据上:

{
  "data": {
    "organization": {
      "repositories": {
        "nodes": [{
            "pullRequests": {
              "totalCount": 2
            }
          },
          {
            "pullRequests": {
              "totalCount": 8
            }
          },
          {
            "pullRequests": {
              "totalCount": 23
            }
          }
        ]
      }
    }
  }
}

我会得到正确的结果。

但目前在 jq-1.6 上我收到以下错误:

jq: error (at <stdin>:24): Cannot iterate over number (2)

我从没有 add 过滤器的输出中注意到,它不是一个数组:

➤ cat pull_requests.json | jq '.data.organization.repositories.nodes[] | .pullRequests.totalCount'
2
8
23

所以我的问题是如何将这些数字相加?

我还尝试使用 [.pullRequests.totalCount] 将其转换为数组,但无法合并、合并、连接数组以获得最终计数。

最佳答案

您错误地认为所示的 jq 过滤器用于处理所示的 JSON。

幸运的是有两个简单的修复:

[ .data.organization.repositories.nodes[]
  | .pullRequests.totalCount ]
| add

或者:

.data.organization.repositories.nodes
| map(.pullRequests.totalCount)
| add

使用西格玛/1

另一种选择是使用面向流的求和函数:

def sigma(s): reduce s as $s (null; .+$s);

.data.organization.repositories.nodes
| sigma(.[].pullRequests.totalCount)

关于stream - 添加非数组格式的数字?或者如何过滤到数组以便我可以总结,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53434228/

相关文章:

java - 如果不匹配,从 ArrayList 流式传输将返回 null 错误

c# - 从流中获取图像时参数无效

javascript - 为什么我不能在 JavaScript 中对 4 个变量进行加法运算,但可以对 3 个变量进行加法运算?

R,在循环中添加数据帧

arrays - 在 JSON-LD 文件中过滤具有特定 JSON 值的键

json - 使用 JQ 从 bash 中的 JSON 对象检索值

c# mocking IFormFile CopyToAsync() 方法

javascript - 使用 javascript 添加总数

jq - 如何查看我最近完成的 Codebuild 构建项目的状态?

FFmpeg CLI - 使用 ZMQ (zmqsend) 交换 RTMP 源