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. 我心中的核心组件(可插拔的AOP)~第六回 消息组件~续

    回到目录 上一回写消息组件已经是很久之前的事了,这一次准备把消息组件后续的东西说一下,事实上,第一篇文章主要讲的是发消息,而这一讲最要讲的是收消息,简单的说,就是消息到了服务器之后,如何从服务器实时的 ...

  2. Thrift架构~动态Thrift插件的注入

    先说AOP 说到注入,大家就会想起来IoC和AOP,确实如些,这一讲中,我们通过unity来实现对thrift插件的动态注入,事实上,这个功能在以后的项目中经常要用到,比如,你将一些功能分发到指定服务 ...

  3. PHP数据库操作:从MySQL原生API到PDO

    本文将举详细例子向大家展示PHP是如何使用MySQL原生API.MySQLi面向过程.MySQLi面向对象.PDO操作MySQL数据库的. 为了后面的测试,先建立数据库表test.包含表名user,s ...

  4. salesforce 零基础开发入门学习(九)Approval Process 介绍

    在阅读此篇文章前,可以先参考阅读一个前辈总结的关于Approval Process的操作.以下为参考的链接: http://www.cnblogs.com/mingmingruyuedlut/p/37 ...

  5. salesforce 零基础开发入门学习(二)变量基础知识,集合,表达式,流程控制语句

    salesforce如果简单的说可以大概分成两个部分:Apex,VisualForce Page. 其中Apex语言和java很多的语法类似,今天总结的是一些简单的Apex的变量等知识. 有如下几种常 ...

  6. POI生成WORD文档

    h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h ...

  7. 使用maven下载jar包的source和javadoc

    使用maven菜单下载sources和javadocs没什么反应,还是命令给力. 使用参数下载源码包与doc包: -DdownloadSources=true 下载源代码jar -DdownloadJ ...

  8. python中常用的函数与库一

    1, collections.deque 在python里如果我们用列表作为队列使用也是可以的,只是当从队尾删除或者增加元素的时候是很快的,但是从队首删除或者增加元素则要慢得多,这是因为在队首进行操作 ...

  9. hibernate(五) hibernate一对一关系映射详解

    序言 之前讲解了一对多(单向.双向).多对多(双向),今天就讲解一下最后一个关系,一对一. 心情不错.状态也挺好的,赶紧写一篇博文造福一下大家把. --WH 一.一对一关系的概述 一对一关系看起来简单 ...

  10. 快速了解SPA单页面应用

    简要 SPA单页网页应用程序这个概念并不算新,早在2003年就已经有在讨论这个概念了,不过,单页应用这个词是到了2005年才有人提出使用,SPA的概念就和它的名字一样显而易懂,就是整个网站不再像传统的 ...