Accessing a JSON object in Bash – associative array / list / another model

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
do
    myarray[$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[@]}"
do
    echo "$key = ${myarray[$key]}"
done

For this given input, it returns:

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

Leave a Comment