设为首页 加入收藏

TOP

HTTPResponse object — JSON object must be str, not 'bytes'(一)
2017-09-30 17:40:13 】 浏览:4614
Tags:HTTPResponse object JSON must str not ' bytes'

http://stackoverflow.com/questions/24069197/httpresponse-object-json-object-must-be-str-not-bytes

 

I've been trying to update a small Python library called libpynexmo to work with 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:

TypeError: the JSON object must be str, not 'bytes'

I read in a few places that for json.load you should pass objects (In this case an HTTPResponseobject) with a .read() attached, but it doesn't work on HTTPResponse objects.

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.

share improve this question
 
5  
    
did you try passing it through 2to3? – zmo Jun 5 '14 at 20:03
    
@zmo - Did it manually so I could learn more. – Chevron Jun 5 '14 at 20:24
    
@dano - Found that link earlier, but was unable to make his workaround apply to my situation. I am unable to use .readall() on my HTTPResponse object. – Chevron Jun 5 '14 at 20:26
2  
@Chevron, if you're trying to convert the json request object, then use this: json.loads(request.b??ody.decode('utf-8')) – Anshuman Biswas May 28 '15 at 0:37 

4 Answers

up vote 13down voteaccepted

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 = j
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python中的file和open简述 下一篇Python-Day4 Python基础进阶之生..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目