2016-11-27 58 views
0

我想用Python解碼JSON。這是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

也可以考慮使用['requests'(HTTP:// docs.python-requests.org/en/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去第一的那些和提取數據你要。

如果你需要提取這些數據點每個字典在該列表中,你必須使用一個循環:

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

啊......我真是個傻瓜!謝謝!我想我現在可以通過JSON從'0'循環到'n'? – Rachel

+1

@Rachel:Python循環是foreach結構,當你直接訪問序列中包含的元素時,不需要使用索引。 –