Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct JSON with a variable key using jq

Tags:

json

jq

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
like image 966
Joshua Spence Avatar asked Mar 07 '16 10:03

Joshua Spence


People also ask

Can jq create JSON?

jq is a command-line utility that can slice, filter, and transform the components of a JSON file. Many users rely on jq to properly format JSON files because it always displays JSON information in a “pretty” format.

What does jq command do?

jq is a lightweight and flexible command-line JSON processor. jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

What is the output of jq?

jq usually outputs non-ASCII Unicode codepoints as UTF-8, even if the input specified them as escape sequences (like "\u03bc"). Using this option, you can force jq to produce pure ASCII output with every non-ASCII character replaced with the equivalent escape sequence.


2 Answers

Use parentheses to evaluate $key early as in:

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

See also: Parentheses in JQ for .key

like image 50
Hans Z. Avatar answered Sep 29 '22 12:09

Hans Z.


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"}'
like image 45
Inian Avatar answered Sep 29 '22 11:09

Inian