Evgenii Evgenii - 4 months ago 31
JSON Question

Converting a JSON array to a bash Array

I have a bash script. It gets data in JSON.
I need to convert the JSON array to a bash array.


"SALUTATION": "Hello world",
"SOMETHING": "bla bla bla Mr. Freeman"

In bash I wanna get value like this
echo ${arr[SOMETHING]}


If you want key and value, and based on How do i convert a json object to key=value format in JQ, you can do:

$ jq -r "to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]" file
SALUTATION=Hello world
SOMETHING=bla bla bla Mr. Freeman

In a more general way, you can store the values into an array myarray[key] = value like this, just by providing jq to the while with the while ... do; ... done < <(command) syntax:

declare -A myarray
while IFS="=" read -r key value
done < <(jq -r "to_entries|map(\"\(.key)=\(.value)\")|.[]" file)

And then you can loop through the values like this:

for key in "${!myarray[@]}"
    echo "$key = ${myarray[$key]}"

For this given input, it returns:

SALUTATION = Hello world
SOMETHING = bla bla bla Mr. Freeman