如何使用Python解码JSON?

时间:2016-11-27 16:14:05

标签: python json python-3.x decode

我正在尝试使用Python解码JSON。以下是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

为什么?我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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来获取第一个字段并提取所需的数据。< / p>

如果您需要为该列表中的每个字典提取这些数据点,您必须使用循环:

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