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