简体   繁体   中英

How to parse and loads JSON in bash shell script?

I am trying to loads and print JSON response in shell script.I dont have any idea how to achieve this.Please help me on this.

Code:

#!/bin/sh

malop_q=$(curl -X GET -k -H "SEC: xxxxxxxxxxxxxxxxxxxxxx" 'https://127.0.0.1/api/reference_data/sets/malopid?fields=data(value)')

echo $malop_q

JSON Response:

{"data":[{"value":"11.945403842773683082"},{"value":"11.945403842773683082"},{"value":"11.945403842773683082"}]}

Expected OP is

I need to print values from above JSON response is:

11.945403842773683082
11.945403842773683082
11.945403842773683082

Thanks in advance.

'

The following python code do the parsing, assuming that you save it as: my_json.py

import json,sys

obj=json.load(sys.stdin)
for i in range(len(obj['data'])):
    print obj['data'][i]['value']

You can get the respond using:

malop_q=$(curl -X GET -k -H "SEC: xxxxxxxxxxxxxxxxxxxxxx" 'https://127.0.0.1/api/reference_data/sets/malopid?fields=data(value)')   
echo $malop_q | python my_json.py

or in one line:

curl -X GET -k -H "SEC: xxxxxxxxxxxxxxxxxxxxxx" 'https://127.0.0.1/api/reference_data/sets/malopid?fields=data(value)' | python my_json.py

With Python :

import json

with open('file.json') as json_file:    
    datas = json.load(json_file)

for d in datas["data"]:
  print(d["value"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM