Construct JSON with a variable key using jq

Viewed 10599

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
2 Answers

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"}'
Related