The docs certainly make it sound like it does not. But, I can’t think of any way to explain the behavior below. What am I doing wrong?
On some cluster data, I am trying to show the total number of cpus being used out of the total available. I want to iterate through the array of objects in o.json
and compute the difference between two values (.cpus.total - .cpus.allocated
) and display the sum of those deltas as well as the sum of one of the values (.cpus.total
).
So .[].cpus.total
will spit out a list of integers:
$ cat /tmp/o.json | jq -c '[.[].cpus.total]|add'
2764
But when I do the same thing after a map statement, it errors:
$ cat /tmp/o.json | jq -c '[(map(.cpus.total - .cpus.allocated) | add), "/", [.[].cpus.total]|add]'
jq: error (at <stdin>:13762): Cannot iterate over number (2556)
That error makes it sound like “add” wanted an array but didn’t get one. And sure enough, forcing it into an array (and then taking the zero’th value, because it is just an integer) works:
$ cat /tmp/o.json | jq -c '[(map(.cpus.total - .cpus.allocated) | add), "/", [[.[].cpus.total]|add][0] ]'
[2556,"/",2764]
At this point I have working code but I don’t understand why I needed that extra set of square brackets to get it to go, but only if there is a map earlier in the program. What gives?
Chip Seraphine is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.