gpt4 book ai didi

python - 将 HTTPResponse 对象转换为字典

转载 作者:太空宇宙 更新时间:2023-11-04 03:45:26 24 4
gpt4 key购买 nike

我试图将这个对象变成我可以在我的程序中使用的东西。我需要将消息 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

也许我做错了。将此对象转换为字典或其他我可以轻松使用的东西的最快方法是什么?

最佳答案

通过 json.load() 加载它:

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

关于python - 将 HTTPResponse 对象转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24092602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com