添加不是数组格式的数字?或者如何过滤到数组以便我总结
Adding numbers that are not in array format? Or how to filter to array so I can sum up
在以前的 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)
在以前的 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)