HTTPResponse 对象 -- JSON 对象必须是 str,而不是 'bytes'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24069197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTTPResponse object -- JSON object must be str, not 'bytes'
提问by Chevron
I've been trying to update a small Python library called libpynexmoto work with Python 3.
我一直在尝试更新一个名为libpynexmo的小型 Python 库以使用 Python 3。
I've been stuck on this function:
我一直坚持这个功能:
def send_request_json(self, request):
url = request
req = urllib.request.Request(url=url)
req.add_header('Accept', 'application/json')
try:
return json.load(urllib.request.urlopen(req))
except ValueError:
return False
When it gets to this, json responds with:
当它到达时,json 响应:
TypeError: the JSON object must be str, not 'bytes'
I read in a few places that for json.loadyou should pass objects (In this case an HTTPResponseobject) with a .read()attached, but it doesn't work on HTTPResponseobjects.
我在几个地方读到json.load你应该传递HTTPResponse带有.read()附加的对象(在这种情况下是一个对象),但它不适用于HTTPResponse对象。
I'm at a loss as to where to go with this next, but being that my entire 1500 line script is freshly converted to Python 3, I don't feel like going back to 2.7.
我不知道下一步该往哪里走,但由于我的整个 1500 行脚本都刚刚转换为 Python 3,我不想回到 2.7。
采纳答案by Ryan
I recently wrote a small function to send Nexmo messages. Unless you need the full functionality of the libpynexmo code, this should do the job for you. And if you want to continue overhauling libpynexmo, just copy this code. The key is utf8 encoding.
我最近写了一个小函数来发送 Nexmo 消息。除非您需要 libpynexmo 代码的全部功能,否则这应该为您完成工作。如果您想继续检修 libpynexmo,只需复制此代码即可。关键是utf8编码。
If you want to send any other fields with your message, the full documentation for what you can include with a nexmo outbound message is here
如果您想随消息发送任何其他字段,有关您可以包含在 nexmo 出站消息中的内容的完整文档在此处
Python 3.4 tested Nexmooutbound (JSON):
Python 3.4 测试了Nexmo出站 (JSON):
def nexmo_sendsms(api_key, api_secret, sender, receiver, body):
"""
Sends a message using Nexmo.
:param api_key: Nexmo provided api key
:param api_secret: Nexmo provided secrety key
:param sender: The number used to send the message
:param receiver: The number the message is addressed to
:param body: The message body
:return: Returns the msgid received back from Nexmo after message has been sent.
"""
msg = {
'api_key': api_key,
'api_secret': api_secret,
'from': sender,
'to': receiver,
'text': body
}
nexmo_url = 'https://rest.nexmo.com/sms/json'
data = urllib.parse.urlencode(msg)
binary_data = data.encode('utf8')
req = urllib.request.Request(nexmo_url, binary_data)
response = urllib.request.urlopen(req)
result = json.loads(response.readall().decode('utf-8'))
return result['messages'][0]['message-id']
回答by costas
Facing the same problem I solve it using decode()
面对同样的问题,我使用 decode() 解决了它
...
rawreply = connection.getresponse().read()
reply = json.loads(rawreply.decode())
回答by Du Peng
I met the problem as well and now it pass
我也遇到了这个问题,现在它通过了
import json
import urllib.request as ur
import urllib.parse as par
html = ur.urlopen(url).read()
print(type(html))
data = json.loads(html.decode('utf-8'))
回答by fedorqui 'SO stop harming'
Since you are getting a HTTPResponse, you can use Tornado.escapeand its json_decode()to convert the JSON strign into a dictionary:
由于您正在获得HTTPResponse,您可以使用Tornado.escape及其json_decode()将 JSON strign 转换为字典:
from tornado import escape
body = escape.json_decode(body)
From the manual:
从手册:
tornado.escape.json_decode(value)
Returns Python objects for the given JSON string.
tornado.escape.json_decode(value)
返回给定 JSON 字符串的 Python 对象。

