如何在bash shell脚本中解析和加载JSON?

时间:2016-05-31 07:48:51

标签: python json bash shell api

我正在尝试在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

提前致谢。

'

2 个答案:

答案 0 :(得分: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 :(得分:2)

使用Python:

import json

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

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