I have a Bash script which gets data in JSON, I want to be able to convert the JSON into an accessible structure - array / list / or other model which would be easy to parse the nested data.
Example:
{ "SALUTATION": "Hello world", "SOMETHING": "bla bla bla Mr. Freeman" }
I want to get the value like the following: echo ${arr[SOMETHING]}
[ Different approach is optional as well. ]
Bash, however, includes the ability to create associative arrays, and it treats these arrays the same as any other array. An associative array lets you create lists of key and value pairs, instead of just numbered values.
A JSON object is produced by assigning an associative PHP array into a JSON domain tree path. A PHP array is associative if it contains one or more string keys, or if it has integer keys that are not contiguously sequenced from 0 to n -1 .
The best way to sort a bash associative array by VALUE is to NOT sort it. Instead, get the list of VALUE:::KEYS, sort that list into a new KEY LIST, and iterate through the list. Show activity on this post. Show activity on this post.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With