Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through json in bash script

Tags:

json

bash

I have the json as below, i need to get only the mail from the above json in bash script

value={"count":5,"users":[{"username":"asa","name":"asa Tran","mail":"[email protected]"},{"username":"qq","name":"qq Morris","mail":"[email protected]"},{"username":"qwe","name":"qwe Org","mail":"[email protected]"}]}

Output can be as

[email protected],[email protected],[email protected]

All the above need to be done in the bash script (.sh)

I have already tried with the array iteration as but of no use

for key in "${!value[@]}"
do
        #echo "key = $key"
        echo "value = ${value[$key]}"
done

Even i have tried with the array conversion as

alias json-decode="php -r 'print_r(json_decode(file_get_contents(\"php://stdin\"),1));'" value=$(curl --user $credentials -k $endPoint | json-decode)

Still i was not able to get the specific output.

like image 994
Sarang Avatar asked Oct 21 '13 07:10

Sarang


2 Answers

jq is the tool to iterate through a json. In your case:

while read user; do
    jq -r '.mail' <<< $user
done <<< $(jq -c '.users[]' users.json)

would give:

[email protected]
[email protected]
[email protected]

NOTE: I removed "value=" because that is not valid json. Users.json contains:

{"count":5,"users":[{"username":"asa","name":"asa Tran","mail":"[email protected]"},{"username":"qq","name":"qq Morris","mail":"[email protected]"},{"username":"qwe","name":"qwe Org","mail":"[email protected]"}]}
like image 146
Chris Maes Avatar answered Sep 24 '22 03:09

Chris Maes


If this is valid json and the email field is the only one containing a @ character, you can do something like this:

echo $value | tr '"' '\n' | grep @

It replaces double-quotes by new line character and only keeps lines containing @. It is really not json parsing, but it works.

You can store the result in a bash array

emails=($(echo $value | tr '"' '\n' | grep @))

and iterate on them

for email in ${emails[@]}
do
    echo $email
done
like image 26
cbliard Avatar answered Sep 20 '22 03:09

cbliard