itchyny / gojq

Pure Go implementation of jq
MIT License
3.3k stars 119 forks source link

Question on the use of "as" in v0.12.16 #260

Closed nathanmcgarvey-modopayments closed 3 months ago

nathanmcgarvey-modopayments commented 3 months ago

Noticed some expressions stop being valid (using "as") in v0.12.16 and was having trouble tracking down the commit that causes this between v0.12.15->v0.12.16. Was hoping someone could shed light on if this is a regression or expected change:

Note the container versions:

% echo '{"foo": {"bar": "thisIsSilly"}}' | docker run -i --rm itchyny/gojq:0.12.15 '.foo | .bar + "bat" as $baz | $baz'
"thisIsSillybat"

% echo '{"foo": {"bar": "thisIsSilly"}}' | docker run -i --rm itchyny/gojq:0.12.16 '.foo | .bar + "bat" as $baz | $baz'
gojq: invalid query: .foo | .bar + "bat" as $baz | $baz
    .foo | .bar + "bat" as $baz | $baz
                        ^  unexpected token "as"

% echo '{"foo": {"bar": "thisIsSilly"}}' | docker run -i --rm itchyny/gojq:0.12.16 '.foo | (.bar + "bat") as $baz | $baz'
"thisIsSillybat"
nathanmcgarvey-modopayments commented 3 months ago

Figured out the exact commit:

https://github.com/itchyny/gojq/commit/01355e9509c093fa4d7e18bb15315d6acf4dfa19

works:

go: downloading github.com/itchyny/gojq v0.12.16-0.20240519045059-a41a5f82f601
"thisIsSillybat"

doesn't work:

%  echo '{"foo": {"bar": "thisIsSilly"}}' | go run github.com/itchyny/gojq/cmd/gojq@01355e9509c093fa4d7e18bb15315d6acf4dfa19 '.foo | .bar + "bat" as $baz | $baz'
go: downloading github.com/itchyny/gojq v0.12.16-0.20240521102931-01355e9509c0
gojq: invalid query: .foo | .bar + "bat" as $baz | $baz
    .foo | .bar + "bat" as $baz | $baz
                        ^  unexpected token "as"
exit status 3

Edit: formatting.

itchyny commented 3 months ago

This is an unintentional side effect of extending the syntax, however pretty reasonable change, so I'm closing this issue. The query is confusing because the binary operator precedence is lower than the pipe operator only when the right hand side is bound. For example, 1 + 1 | -. is (1 + 1) | -. but 1 + 1 as $x | -$x is 1 + (1 as $x | -$x). Your examples ironically prove this complexity; .foo | .bar + "bat" as $baz | $baz in v0.12.15 is not interpreted as .foo | (.bar + "bat") as $baz | $baz. Please use parenthesis to resolve the ambiguity.

nathanmcgarvey-modopayments commented 3 months ago

Thanks for the quick response. That parenthetical addition to remove ambiguity is what I did. Just noticed the issue and wanted to ensure it was intended.