Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq & bash: make JSON array from variable

Tags:

I'm using jq to form a JSON in bash from variable values.

Got how to make plain variables

$ VAR="one two three" $ jq -n "{var:\"$VAR\"}" {   "var": "one two three" } 

But can't make arrays yet. I have

$ echo $ARR one two three 

and want to get something like

{   "arr": ["one", "two", "three"] } 

I only manage to get garbled output like

$ jq -n "{arr: [\"$ARR\"]}" {   "arr": [     "one\ntwo\nthree"   ] } 

How to form JSON array in a correct way? Can jq ever do that?

EDIT: Question was asked when there was only jq 1.3. Now, in jq 1.4, it is possible to do straightly what I asked for, like @JeffMercado and @peak suggested, upvote for them. Won't undo acceptance of @jbr 's answer though.

like image 774
Andrey Regentov Avatar asked Mar 16 '14 07:03

Andrey Regentov


People also ask

What is jq?

The JQ command is used to transform JSON data into a more readable format and print it to the standard output on Linux. The JQ command is built around filters which are used to find and print only the required data from a JSON file.

What is jq bash?

jq is a powerful tool that lets you read, filter, and write JSON in bash.

What does jq stand for JSON?

jq (as in jq) is a "JSON query language" and might perhaps therefore have been called "JQL" by analogy with "SQL", but jq is shorter :-) Also note that jq is not only a JSON query language, but completely subsumes JSON: any valid JSON expression is a valid jq expression.


1 Answers

In jq 1.3 and up you can use the --arg VARIABLE VALUE command-line option:

jq -n --arg v "$VAR" '{"foo": $v}' 

I.e., --arg sets a variable to the given value so you can then use $varname in your jq program, and now you don't have to use shell variable interpolation into your jq program.

EDIT: From jq 1.5 and up, you can use --argjson to pass in an array directly, e.g.

jq -n --argjson v '[1,2,3]' '{"foo": $v}' 
like image 54
user2259432 Avatar answered Sep 28 '22 02:09

user2259432