Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. ]

like image 805
Evgenii Avatar asked Nov 03 '14 15:11

Evgenii


People also ask

Does bash have associative arrays?

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.

Is JSON associative array?

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 .

How do you sort an associative array in bash?

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.


1 Answers

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 
like image 181
fedorqui 'SO stop harming' Avatar answered Oct 04 '22 18:10

fedorqui 'SO stop harming'