Jq: Use jq argument as a JSON key

Created on 12 May 2020  路  2Comments  路  Source: stedolan/jq

I couldn't find any issue with this already.

I think the following statement is supposed to work, but it doesn't.

version_key="version"
$ echo '{ "version": "1.1.1" }' | jq --arg v "$version_key" '.$v'
jq: error: syntax error, unexpected '$' (Unix shell quoting issues?) at <top-level>, line 1:
.$v
jq: error: try .["field"] instead of .field for unusually named fields at <top-level>, line 1:
.$v
jq: 2 compile errors

However, there is how to work around it by not using jq arguments at all:

version_key="version"
$ echo '{ "version": "1.1.1" }' | jq ".$version_key"
"1.1.1"

Or is this the intended behavior?

Most helpful comment

The .foo notation can only be used under certain very restricted circumstances. The general "get value" syntax is .[STRING] where STRING can be a string-valued variable. For example:

$ version_key="version"
$ echo '{ "version": "1.1.1" }' | jq --arg v "$version_key" '.[$v]'
"1.1.1"

There are numerous variations.

In future, if at all possible, please post jq usage questions to stackoverflow.com using the jq tag:
https://stackoverflow.com/questions/tagged/jq

All 2 comments

The .foo notation can only be used under certain very restricted circumstances. The general "get value" syntax is .[STRING] where STRING can be a string-valued variable. For example:

$ version_key="version"
$ echo '{ "version": "1.1.1" }' | jq --arg v "$version_key" '.[$v]'
"1.1.1"

There are numerous variations.

In future, if at all possible, please post jq usage questions to stackoverflow.com using the jq tag:
https://stackoverflow.com/questions/tagged/jq

Amazing! This solves the problem I described.

I initially thought it was a bug, that's why I posted here. Thank you for pointing the right place.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

neowulf picture neowulf  路  3Comments

lbrader picture lbrader  路  3Comments

thelonious picture thelonious  路  4Comments

sloanlance picture sloanlance  路  3Comments

ve3ied picture ve3ied  路  4Comments