将HTTPResponse对象转换为字典

时间:2014-06-07 00:55:24

标签: python python-3.x dictionary httpresponse

我试图将这个对象变成我可以在我的程序中使用的东西。我需要将message-id存储到数据库中。如果没有完全解析它,我能不能以某种方式将整个事情变成字典?

以下是我进行IDLE测试的地方:

>>> response = urllib.request.urlopen(req)
>>> response.getheaders()
[('Server', 'nginx/1.6.0'), ('Date', 'Sat, 07 Jun 2014 00:32:45 GMT'), ('Content-Type', 'application/json;charset=ISO-8859-1'), ('Transfer-Encoding', 'chunked'), ('Connection', 'close'), ('Cache-Control', 'max-age=1')]
>>> response.read()
b'{"message-count":"1","messages":[{"to":"11234567890","message-id":"02000000300D8F21","status":"0","remaining-balance":"1.82720000","message-price":"0.00620000","network":"302220"}]}'

经过谷歌筛选半小时后,我可以将其变成一个字符串:

>>> response.response.decode('utf-8')
>>> print(response)
'{"message-count":"1","messages":[{"to":"11234567890","message-id":"02000000300D8F21","status":"0","remaining-balance":"1.82720000","message-price":"0.00620000","network":"302220"}]}'
>>> type(response)
<class 'str'>

我找到this post,但这是我得到的:

>>> a_dict = dict([response.strip('{}').split(":"),])
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
  a_dict = dict([response.strip('{}').split(":"),])
ValueError: dictionary update sequence element #0 has length 9; 2 is required

也许我说这一切都错了。什么是将这个对象变成字典或其他我可以轻松使用的其他东西的最快方法?

1 个答案:

答案 0 :(得分:2)

通过json.load()

加载
import json
response = urllib.request.urlopen(req)
result = json.loads(response.readall().decode('utf-8'))
message_id = result['messages'][0]['message-id']