Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQ Create JSON Key and Value Pair

I'm trying to create a JSON file with this very simple command:

jq -n --arg greeting world --arg mykey hello '{"hello":$greeting}'

My problem is that when I replace the key with $mykey I get this error:

# jq -n --arg greeting world --arg mykey hello {$mykey:$greeting}
jq: error: syntax error, unexpected ':' (Unix shell quoting issues?) at <top-level>, line 1:
{:}
jq: 1 compile error

How can I create a simple JSON file with two arguments/variables?

like image 262
Ken J Avatar asked Sep 16 '25 07:09

Ken J


1 Answers

As explained in the jq manual, when a key name is specified programmatically, the defining expression must be enclosed in parentheses:

$ jq -n --arg greeting world --arg mykey hello '{($mykey):$greeting}'
{
  "hello": "world"
}
like image 87
peak Avatar answered Sep 18 '25 08:09

peak