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

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

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


up vote17down votefavorite

7

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.

json python-3.x python-3.4 nexmo


shareimprove this question

edited Aug 7 ‘14 at 4:01

Emrakul

3,73152659

asked Jun 5 ‘14 at 19:59

Chevron

132129

 

5  

See here for a solution: stackoverflow.com/questions/6862770/… – dano Jun 5 ‘14 at 20:03 
    

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 

show 1 more comment

4 Answers

activeoldestvotes


up vote13down 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 = json.loads(response.readall().decode(‘utf-8‘))
    return result[‘messages‘][0][‘message-id‘]

shareimprove this answer

edited Jun 29 ‘15 at 20:51

Aereaux

6501617

answered Jun 6 ‘14 at 1:01

miR

393413

 
add a comment


up vote30down vote

Facing the same problem I solve it using decode()

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

shareimprove this answer

answered Jul 1 ‘14 at 18:41

costas

309123

 

13  

Can you explain why this is necessary? – skaz Jun 26 ‘15 at 8:45

add a comment


up vote5down vote

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

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

时间: 2024-11-09 01:43:35

HTTPResponse object — JSON object must be str, not 'bytes'的相关文章

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

json.loads(json_data)报错 修改为json.loads(json_data.decode())即可 一些修改为load什么的方法会带来新的报错… 直接添加decode()解决 描述 Python decode() 方法以 encoding 指定的编码格式解码字符串.默认编码为字符串编码. 语法 decode()方法语法: str.decode(encoding='UTF-8',errors='strict') 参数 encoding -- 要使用的编码,如"UTF-8&quo

如果一个json string中含有“class”这个key, 那么利用JSONObjec.fromObject(string)得到的一个json object会丢失“class”信息

查看net.sf.json.JSONObject的source code, 发现JSONObject.fromObject()的内部 有这样的处理:如果json key是"class",那么这个json object不添加这个property. 解决办法: 1. 修改source code 2. 用Gson, json.simple等代替JSONObject

XML,Object,Json转换之浅析Xstream的使用

XML,Object,Json转换之浅析Xstream的使用 请尊重他人的劳动成果,转载请注明出处:XML,Object,Json转换之浅析Xstream的使用 XStream的是一个简单的库,主要用于Java对象和XML之间的转换.但XStream也内置了对Json的支持. 1.Xstream的特点: 这里直接引用Xstream官方的叙述: 灵活易用:在更高的层次上提供了简单.灵活.易用的统一接口,用户无需了解项目的底层细节 无需映射:大多数对象都可以在无需映射的情况下进行序列化与反序列化的操

python读取json文件报 No JSON object could be decoded

def load(): with open('D:\\jiance.geojson') as json_file: data = json.load(json_file) return data 代码如上,读取json并load时报错: No JSON object could be decoded 解决方法: 可用Nodepad++将json文件打开并以UTF8无BOM格式保存,然后再次读取

WINDOWS下,中文JSON格式读取报错处理:ValueError: No JSON object could be decoded

File "C:\Python27\lib\json\__init__.py", line 290, in load **kw) File "C:\Python27\lib\json\__init__.py", line 351, in loads return cls(encoding=encoding, **kw).decode(s) File "C:\Python27\lib\json\decoder.py", line 365, in d

Adding property to a json object in C#

Adding property to a json object in C# you can do it with a dynamic object dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(jsonString); obj.Values.valueName4 = "value4"; System.Console.WriteLine(JsonConvert.SerializeObject(obj))

object(DOMNodeList) object(DOMElement)

获取api的时候,获取回来的特殊对象 $eBayTime = $responseDoc->getElementsByTagName('Timestamp'); object(DOMNodeList)    $eBayTime 这种对象,取长度 $eBayTime->length 取值   $eBayTime->item(0) 取值的对象是 object(DOMElement) $eBayTime->item(0) 取值       $eBayTime->item(0)->

JavaScript中object和Object有什么区别

JavaScript中object和Object有什么区别,为什么用typeof检测对象,返回object,而用instanceof 必须要接Object呢 -------------------------------------------------------------------- 这个问题和我之前遇到的问题非常相似,我认为这里有两个问题需要解决,一个是运算符new的作用机制,一个是function关键字和Funtion内置对象之间的区别.看了一些前辈的博客和标准,这里帮提问者总结一

java之Thread.sleep(long)与object.wait()/object.wait(long)的区别(转)

一.Thread.sleep(long)与object.wait()/object.wait(long)的区别sleep(long)与wait()/wait(long)行为上有些类似,主要区别如下:1.Thread.sleep(long)是属于Thread类的静态方法.其基本语义是使当前运行的线程暂停一段时间.实现细节是把当前线程放入就绪线程队列中,直到睡眠时间到期才可被调度为执行线程(在时间到期前无法被调度为执行线程).此方法可以在sychronized代码块中,调用此方法不释放对象锁:也可以