Can not manipulate a argjson argument in jq

Advertisements

having a bigger problem that basically comes down to some difference between types of arguments.

These work:

$ echo '{ "options": [ { "a": "b" } ] }' | jq -c '.options += [ { "c": "d" } ] | .options'
[{"a":"b"},{"c":"d"}]
$

and

$ jq -c --null-input '{ "options": [ { "a": "b" } ] } | .options += [ { "c": "d" } ] | .options'
[{"a":"b"},{"c":"d"}]
$

and:

$ jq -c --null-input --argjson options '[ { "a": "b" } ]' '$options[0].a'
"b"
$

But this does not:

$ jq -c --null-input --argjson options '[ { "a": "b" } ]' '$options += [ { "c": "d" } ] | $options'
jq: error (at <unknown>): Invalid path expression with result [{"a":"b"}]
$

I need the argjson defined var to gather objects mutually overriding each other, traversing a recursive JSON structure as that is the only way I found that, across functions, should work(tm).

I’m totally aware that I’m doing something wrong, so the blame is all mine, but this costed me too much time already, so I will be eternally thankfull for some angel showing me the errors of my ways.

>Solution :

You’re trying to change $options, but assignments aren’t done that way. An assignment is done using ... as $var | .... So your code should be

( $options + [ { "c": "d" } ] ) as $options | $options

That said, there’s no reason to change $options here, so you could use the following:

$options + [ { "c": "d" } ]

You mentioned wanting to use +=.

$options + [ { "c": "d" } ]

can also be written as

$options | . + [ { "c": "d" } ]

But you could also use

$options | . += [ { "c": "d" } ]

Leave a ReplyCancel reply