Danilo Cabello
Danilo Cabello

Reputation: 2963

Adding numbers that are not in array format? Or how to filter to array so I can sum up

In previous versions of jq I was able to run the following:

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

On this sample data:

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

And I would get the correct result.

But currently on jq-1.6 I am getting the following error:

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

What I noticed from the output without the add filter is that is not an array:

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

So my question is how to add these numbers up?

I also tried casting it to array by using [.pullRequests.totalCount] but I was unable to merge, meld, join the arrays to get the final count.

Upvotes: 2

Views: 428

Answers (1)

peak
peak

Reputation: 116900

You are mistaken in thinking that the jq filter as shown used to work on the JSON as shown.

There are fortunately two simple fixes:

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

or:

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

Using sigma/1

Another option is to use a stream-oriented summation function:

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

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

Upvotes: 3

Related Questions