Reputation: 772
I am trying to use jq
to construct a hash in which a key name comes from a variable. Something like this:
jq --null-input --arg key foobar '{$key: "value"}'
This doesn't work, however, and gives the following error:
error: syntax error, unexpected '$'
{$key: "value"} 1 compile error
Upvotes: 24
Views: 15449
Reputation: 85895
You can also use String interpolation in jq
which is of the form "\(..)"
. Inside the string, you can put an expression inside parens after a backslash. Whatever the expression returns will be interpolated into the string.
You can do below. The contents of the variable key
is expanded and returned as a string by the interpolation sequence.
jq --null-input --arg key foobar '{ "\($key)": "value"}'
Upvotes: 3
Reputation: 54088
Use parentheses to evaluate $key
early as in:
jq --null-input --arg key foobar '{($key): "value"}'
See also: Parentheses in JQ for .key
Upvotes: 43