2016-11-27 13 views
0

JSONをPythonでデコードしようとしています。 JSONの外観のちょっとした抜粋です。PythonでJSONをデコードするには?

b'{"success":true,"data":[{"id":26,"name":"A","comment":"","start_time_plan":null,"start_time_actual":"2016-09-13 00:00:00","start_time_delta":null,"start_time_score":null,"start_time_score_achievement":null,"start_time_traffic_light":null,"end_time_plan":null,"end_time_actual":"2016-09-13 00:00:00","end_time_delta":null,"end_time_score":null,"end_time_score_achievement":null,"end_time_traffic_light":null,"status":0,"measure_schedule_revision_id":63,"responsible_user_id":3,"created_time":"2016-09-13 11:29:14","created_user_id":3,"modified_time":"2016-09-21 16:33:41","modified_user_id":3,"model":"Activity"},{"id":27,"name":"B","comment":"","start_time_plan":null,"start_time_actual":"2016-09-13 00:00:00","start_time_delta":null,"start_time_score":null,"start_time_score_achievement":null,"start_time_traffic_light":null,"end_time_plan":null,"end_time_actual":"2016-09-13 00:00:00","end_time_delta":null,"end_time_score":null,"end_time_score_achievement":null,"end_time_traffic_light":null,"status":0,"measure_schedule_revision_id":63,"responsible_user_id":3,"created_time":"2016-09-13 11:29:48","created_user_id":3,"modified_time":"2016-10-16 18:14:36","modified_user_id":1,"model":"Activity"} 

私はstart_time_deltaend_time_deltaのホールドを取得し、少しの散布図を作成しようとしています。しかし、何とか私はJSONをデコードできません。ここで

は、私が何をすべきかです:

#falcon api 
u = 'https://myurl.com' 

#urllib3 + poolmanager for requests 
import urllib3 
http = urllib3.PoolManager() 

import json 
r = http.request('GET', u) 
json.loads(r.data.decode('utf-8')) 

end = json.loads(r.data['end_time_delta']) 
start = json.loads(r.data['start_time_delta']) 

これは私が取得エラーです:バイトのインデックスは来る方法

をstrがない、整数またはスライスでなければなりませんか?そして、どのように問題を解決するのですか?

+0

考える:あなたはそのリスト内のすべての辞書ためにそれらのデータ点を抽出する必要がある場合は

、あなたはループを使用する必要があると思います// docs.python-requests.org/ja/master/)モジュールを使用して、プーリングを自動的に処理し、要求によって返されたJSONを解析する非常に簡単な方法を提供します。 – pzp

答えて

3

あなたはここにjson.loads()の戻り値を無視している:

json.loads(r.data.decode('utf-8')) 

をあなたはその後、再び同じ生をデコードし、デコードされたPythonの結果として、それを使用しようとしてみてください。一度json.loads()を呼び出し、そして得られたPythonの辞書を使用します。

result = json.loads(r.data.decode('utf-8')) 
start = result['data'][0]['start_time_delta'] 
end = result['data'][0]['end_time_delta'] 

結果のリストから'data'キーポイントのトップレベルの辞書なので、私はそれらの最初に取得したデータを抽出するために0を使用しましたあなたは欲しい。 [ `requests`](HTTPを使用しても

for entry in result['data']: 
    start = entry['start_time_delta'] 
    end = entry['end_time_delta'] 
    # do something with these two values, before iterating to the next 
+0

ああ...私はそんなに馬鹿だ!ありがとうございました!私は今、 '0'から' n'までJSONをループすることができると思いますか? – Rachel

+1

@Rachel:Pythonループはforeach構造体です。シーケンスの要素に直接アクセスするだけでインデックスを使う必要はありません。 –

関連する問題