How to iterate through json in bash script

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

values ​​= {"counter": 5, "users": [{"username": "ac", "name": "ac Tran" "mail": " asa@xyz.com "}, {"username" : "sq. sq.", "name": "sq. Morris" "mail": " qq@xyz.com "}, {"username": "QWE", "name": "QWE Org", " mail ":" qwe@xyz.com "}]}

The output may be like

mail=asa@xyz.com,qq@xyz.com,qwe@xyz.com

All of the above must be done in a bash script (.sh)

I already tried with iterating the array but not using

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

Even I tried with 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)

However, I could not get a specific conclusion.

+4
source share
4 answers

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

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

It replaces double quotes with a new line character and saves lines containing @. This is not really json parsing, but it works.

You can save the result in a bash array

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

and iterate over them

for email in ${emails[@]}
do
    echo $email
done
+7

json_pp ( debian, libjson-pp-perl)

:

cat file.json | json_pp

json.

, :

#!/bin/bash
MAILS=""  
LINES=`cat test.json | json_pp | grep '"mail"' | sed 's/.* : "\(.*\)".*/\1/'`
for LINE in $LINES ; do
    MAILS="$LINE,$MAILS"
done
echo $MAILS | sed 's/.$//'

:

qwe@xyz.com,qq@xyz.com,asa@xyz.com
+3

Using standard unix toolkit: sedcommand

cat so.json | sed "s/},/\n/g" | sed 's/.*"mail":"\([^"]*\)".*/\1/'
+1
source

With R, you can do it like this:

$ value={"count":5,"users":[{"username":"asa","name":"asa Tran","mail":"asa@xyz.com"},{"username":"qq","name":"qq Morris","mail":"qq@xyz.com"},{"username":"qwe","name":"qwe Org","mail":"qwe@xyz.com"}]}
$ echo $value | R path users | R map path mail
["asa@xyz.com", "qq@xyz.com", "qwe@gyz.com"]
0
source

All Articles