jq & bash: make JSON array from variable

Tags: arrays json bash jq
Question!

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.



Answers

jq is doing exactly what you tell it to do. jq is not a program for generating JSON, but a tool for querying it. What you are doing with the -n switch is just using it as a pretty printer. So if you want it to print an object with an array containing "one", "two", "three" then you have to generate it.

VAR="one two three"
VAR=$(echo $VAR | sed -e 's/\(\w*\)/,"\1"/g' | cut -d , -f 2-)
echo "{var: [$VAR]}"

Update

As Bryan and others mention below it is indeed possible to generate JSON with jq, and from version 1.4, it's even possible to do what the OP ask directly, see for example Jeff's answer.

By : jbr


Also, u can use syntax: jq --arg keyName "MyVal" '.[]."\($keyName)"[] ./JSONFile.js

for input data like [{"MyVal":"Value1","MyVal":Value2,"NotMyVal":"Value3"}];

to get parsed data from JSON with variables.

This example will print: "Value1" "Value2"

By : alexglue


First you have to use -R to read the raw lines and next you have to slurp all values with -s:

$ echo -e "one\ntwo\nthree" | jq -R . | jq -s '{"arr": .}'
{
  "arr": [
    "one",
    "two",
    "three"
  ]
}
By : ceving


This video can help you solving your question :)
By: admin