2016-05-31 17 views
1

シェルスクリプトでJSONレスポンスをロードして印刷しようとしています。これを達成する方法がわかりません。bashシェルスクリプトで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/)を見てください。 'json'を解析するためのテキスト処理ツール(awkのような)を使うことは決して最善の方法ではありません。 '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 

やで1行:

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"]) 
関連する問題