Belka h.j
Belka h.j

Reputation: 65

Dump Json response to a bash variable

I have the following ouput

[
 "notimportant",
     [
       "val1",
       "val2",
       ...,
       "valn"
     ]
]

I'm trying to store every value into a bash string, using jq I tried this

out=''
req=$(curl -s $url)
len=$(echo $req | jq length ) 
for (( i = 0; i < $len; i++ )); do
    element=$(echo $req | jq '.[1]' | jq --argjson i "$i" '.[$i]')
    out=${element}\n${out}
done

which feels clunky and also has a slow performance. I'm trying to dump the values at once without looping on all the elements

Upvotes: 1

Views: 290

Answers (2)

Eric Bolinger
Eric Bolinger

Reputation: 2912

Do you want the values separate by TAB or NEWLINE characters in a single variable? The @tsv function is useful for controlling output:

outTABS=$(curl -s "$url" | jq -r '.[1]|.|@tsv')
outLINE=$(curl -s "$url" | jq -r '.[1]|.[]|[.]|@tsv')

> echo "$outTABS"
val1    val2    valn

> echo "$outLINE"
val1
val2
valn

Upvotes: 2

Cyrus
Cyrus

Reputation: 88601

With an array:

mapfile -t arr < <(curl -s "$url" | jq -r '.[1] | .[]')
declare -p arr

Upvotes: 2

Related Questions