首页 > 解决方案 > 添加不是数组格式的数字?或者如何过滤到数组以便我总结

问题描述

在以前的 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]但我无法合并、融合、加入数组以获得最终计数。

标签: streamaddjq

解决方案


您错误地认为所示的 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)

推荐阅读