Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `jq` trying to `add` to an object in a variable assignment?

Tags:

sh

jq

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
}
like image 706
Johnsyweb Avatar asked Dec 13 '25 13:12

Johnsyweb


1 Answers

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.

like image 111
pmf Avatar answered Dec 16 '25 22:12

pmf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!