如何用 Python 解码 JSON?

How to decode a JSON with Python?

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

怎么会?我该如何解决这个问题?

您在这里忽略了 json.loads() 的 return 值:

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' 键指向 list 结果,我使用 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