Given the following jq pipeline of expressions:
echo '{"foo": 1}' | jq '.foo + 2 as $bar | {$bar}'
I would expect the output:
{
"bar": 3
}
What I get is:
jq: error (at <stdin>:1): number (1) and object ({"bar":2}) cannot be added
What is this object and why is jq
trying to add
to it?
I can resolve this issue with parentheses but I'm still unclear as to what was happening in the original statement:
echo '{"foo": 1}' | jq '(.foo + 2) as $bar | {$bar}'
{
"bar": 3
}
Your first filter was executed as if it had been parenthesized like this
echo '{"foo": 1}' | jq '.foo + (2 as $bar | {$bar})'
Thus, jq tried to add a number (here 1
) to an object (here {"bar":2}
).
This is because the syntax for a variable binding, as noted in the manual's corresponding section, takes on the form ... as $identifier | ...
. It "includes" the pipe and the following expression. This is reflected by the fact that a binding without the following pipe and expression cannot stand alone.