Construct JSON with a variable key using jq

Use parentheses to evaluate $key early as in:

 jq --null-input --arg key foobar '{($key): "value"}'

See also: Parentheses in JQ for .key


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

Tags:

Json

Jq