stream - 添加不是数组格式的数字?或者如何过滤到数组以便我总结
问题描述
在以前的 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
使用 sigma/1
另一种选择是使用面向流的求和函数:
def sigma(s): reduce s as $s (null; .+$s);
.data.organization.repositories.nodes
| sigma(.[].pullRequests.totalCount)
推荐阅读
- r - 插入符号中的其他指标 - PPV、敏感性、特异性
- javascript - 如何在Javascript中创建一个包含任意八位字节的blob
- javascript - Chrome 扩展 HTML5 视频全屏
- maven - 在 Intellij 项目中使用 Nd4j
- ruby-on-rails - 如果最新的迁移相同,Rails 如何知道有待处理的迁移?
- javascript - 需要一个 JSON 对象、数组或文字
- c++ - 在编译时为运行时设置环境变量
- python - 即使安装了 conda 也无法执行 conda 命令
- bash - 作为参数传递给heredoc块内的docker-compose命令时变量不会扩展
- objective-c - 如何获取超类的对象实例