HTTPResponse对象 - JSON对象必须是str,而不是'bytes'

Che*_*ron 26 json python-3.x nexmo python-3.4

我一直在尝试更新一个名为libpynexmo的小型Python库来使用Python 3.

我一直坚持这个功能:

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
Run Code Online (Sandbox Code Playgroud)

当它到达时,json回应:

TypeError: the JSON object must be str, not 'bytes'
Run Code Online (Sandbox Code Playgroud)

我在几个地方读到,json.load你应该传递HTTPResponse带有.read()附件的对象(在这种情况下是一个对象),但它不适用于HTTPResponse对象.

我不知道下一步该怎么做,但由于我的整个1500行脚本刚刚转换为Python 3,我不想回到2.7.

小智 47

面对同样的问题我使用decode()解决它

...
rawreply = connection.getresponse().read()
reply = json.loads(rawreply.decode())
Run Code Online (Sandbox Code Playgroud)

  • 你能解释为什么这是必要的吗? (14认同)

Rya*_*yan 17

我最近写了一个小函数来发送Nexmo消息.除非您需要libpynexmo代码的完整功能,否则这应该可以帮到您.如果您想继续检修libpynexmo,只需复制此代码即可.关键是utf8编码.

如果您想发送包含您的消息的任何其他字段,可以在此处获取包含nexmo出站消息的完整文档

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']
Run Code Online (Sandbox Code Playgroud)


小智 12

我也遇到了这个问题,现在它通过了

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'))
Run Code Online (Sandbox Code Playgroud)