2016-05-31 126 views
1

我想加载和打印shell脚本中的JSON响应。我没有任何想法如何实现this.Please帮助我这一点。如何在bash shell脚本中解析和加载JSON?

代码:

#!/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响应:

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

预期OP是

我需要从上述JSON响应打印值是:

11.945403842773683082 
11.945403842773683082 
11.945403842773683082 

由于在提前。

'

+0

你在寻找“bash only”的答案吗?或者使用python的答案? – Yaron

+2

看看['jq'](https://stedolan.github.io/jq/)。使用文本处理工具(比如'awk')来解析'json'永远不是最好的主意。使用具有'json'解析库的工具。 – anishsane

+0

是的,我只需要bash –

回答

2

以下Python代码做了分析,假设你将它保存为:my_json.py

import json,sys 

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

可以使用得到回应:

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 

或一行:

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

与Python:

import json 

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

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