在 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/