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.

asked Jun 5 '14 at 19:59
Chevron

132129
 
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

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']
answered Jun 6 '14 at 1:01
miR

393413
 

Facing the same problem I solve it using decode()

...
rawreply = connection.getresponse().read()
reply = json.loads(rawreply.decode())
answered Jul 1 '14 at 18:41
costas

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

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'的更多相关文章

  1. python中读取json文件报错,TypeError:the Json object must be str, bytes or bytearray,not ‘TextIOWrapper’

    利用python中的json读取json文件时,因为错误使用了相应的方法导致报错:TypeError:the Json object must be str, bytes or bytearray,n ...

  2. the JSON object must be str, not 'bytes'

    { "ErrorDump": "the JSON object must be str, not 'bytes'", "StatusCode" ...

  3. Python之scrapy框架之post传输数据错误:TypeError: to_bytes must receive a unicode, str or bytes object, got int

    错误名:TypeError: to_bytes must receive a unicode, str or bytes object, got int 错误翻译:类型错误:to_bytes必须接收u ...

  4. json loads No JSON object could be decoded 问题解决

    今天自己用json的 dumps生成的 json 文本: f2=open(filename,'w')f2.write(json.dumps(c) f=open(filename,'r')r= f.re ...

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

    File "C:\Python27\lib\json\__init__.py", line 290, in load **kw) File "C:\Python27\li ...

  6. XML,Object,Json分析转换Xstream采用

    XML,Object,Json转换之浅析Xstream的使用 请尊重他人的劳动成果,转载请注明出处:XML,Object,Json转换之浅析Xstream的使用 XStream的是一个简单的库.主要用 ...

  7. 向json中添加新的熟悉或对象 Add new attribute (element) to JSON object using JavaScript

    How do I add new attribute (element) to JSON object using JavaScript? JSON stands for JavaScript Obj ...

  8. 从零开始——JSON ARRAY&JSON OBJECT

    在学习“基于角色的权限”的例子中,遇到了json object和json array,因此在一番学习之后对此要点进行粗略整理. 参考: https://my.oschina.net/u/2601842 ...

  9. 记一次接口调试错误: {"timestamp":"2019-09-11T03:04:30.036+0000","status":500,"error":"Internal Server Error","message":"Could not write JSON: Object is null; nested exception is com.fasterxml.jackson

    接口测试中用postman测试返回是正常的,但是使用其他人去调用就出错了,找了半天,才想起来使用了nginx,用于端口的代理转发.然后根据错误信息发现json格式的某个字段为null,结合日志中的报文 ...

随机推荐

  1. GUID相关知识

      全局唯一标识符(GUID,Globally Unique Identifier)是一种由算法生成的二进制长度为128位的数字标识符.GUID主要用于在拥有多个节点.多台计算机的网络或系统中.在理想 ...

  2. MVVM架构~knockoutjs系列之为validation.js扩展minLength和maxLength

    返回目录 为什么要对minLength和maxLength这两个方法进行扩展呢,是因为这样一个需求,在用户注册时,可以由用户自己决定他们输入的字符,中文,英文,数字均可,这样做了之后,使用户的体验更好 ...

  3. Gitlab备份、升级、恢复

    一.备份 1.使用Omnibus安装包安装 --gitlab-rake gitlab:backup:create 2.使用源码安装 --./use_gitlab----如果备份失败,PATH路径错误, ...

  4. iOS开发——UI精选OC篇&UIApplication,UIWindow,UIViewController,UIView(layer)简单介绍

    UIApplication,UIWindow,UIViewController,UIView(layer)简单介绍 一:UIApplication:单例(关于单例后面的文章中会详细介绍,你现在只要知道 ...

  5. 在jQuery ajax中按钮button和submit的区别分析

    在使用jQuery ajax的get方法进行页面传值,不能用submit,否则无刷新获取数据展示 点击submit提交按钮,sendPwd.php通过$_POST接收传过来的值,然后echo一段数据. ...

  6. 使用反射将DataTable的数据转成实体类

    利用反射避免了硬编码出现的错误,但是实体类的属性名必须和数据库名字对应(相同) 1.利用反射把DataTable的数据写到单个实体类 /// <summary> ///利用反射把DataT ...

  7. DOM_01之树及遍历

    1.DOM:ECMAScript+DOM+BOM,Document Object Model,核心DOM+HTML DOM+XML DOM: 2.辨析:①HTML:专门编写网页内容的语言:②XHTML ...

  8. java基础-继承:矩形体积类问题

    28.按要求编写一个Java应用程序: (1)定义一个类,描述一个矩形,包含有长.宽两种属性,和计算面积方法. (2)编写一个类,继承自矩形类,同时该类描述长方体,具有长.宽.高属性, 和计算体积的方 ...

  9. hibernate(六) cascade(级联)和inverse关系详解

    序言 写这篇文章之前,自己也查了很多的资料来搞清楚这两者的关系和各自所做的事情,但是百度一搜,大多数博文感觉说的云里雾里,可能博主自己清楚是怎么一回事,但是给一个不懂的人或者一知半解的人看的话,别人也 ...

  10. 解析大型.NET ERP系统 20条数据库设计规范

    数据库设计规范是个技术含量相对低的话题,只需要对标准和规范的坚持即可做到.当系统越来越庞大,严格控制数据库的设计人员,并且有一份规范书供执行参考.在程序框架中,也有一份强制性的约定,当不遵守规范时报错 ...