Evgenii Evgenii - 1 year ago 126
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]}

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download