HTTPResponse object — JSON object must be str, not 'bytes'

跟風遠走 提交于 2019-11-27 12:05:44
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.

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

Python 3.4 tested Nexmo outbound (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']

Facing the same problem I solve it using decode()

...
rawreply = connection.getresponse().read()
reply = json.loads(rawreply.decode())

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'))

Since you are getting a HTTPResponse, you can use Tornado.escape and its json_decode() to convert the JSON strign into a dictionary:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!