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. Vue API阅读的小细节

    #后面是表达式,下面是参数列表,参数列表每行说明一个参数.每行的参数说明,最后边对应表达式的参数,左边是该参数的类型一类的说明.

  2. Java中main()的args的知识点浅谈

    我们先来了解下Java中main()方法的默认定义格式: public static void main(String[] args){ }1.main方法是程序执行的入口,除了args这个形参变量可 ...

  3. 拥抱cnpm

    在国内由于墙的原因,使用NPM安装模块经常会失败,要或在速度上会慢得跟蜗牛一样,这时候我们其实可以选择国内淘宝的NPM镜像,使用下面的命令来进行安装: npm install -g cnpm --re ...

  4. angular测试-Karma + Jasmine配置

    首先讲一下大致的流程: 需要node环境,首先先要安装node,node不会?请自行搜索.版本>0.8 安装node完成之后先要测试下npm是否测试通过,如下图所示 首先看下目录结构 目录为:F ...

  5. 为什么GOF的23种设计模式里面没有MVC?

    GoF (Gang of Four,四人组, <Design Patterns: Elements of Reusable Object-Oriented Software>/<设计 ...

  6. http的500,502,504错误

    500 500的错误通常是由于服务器上代码出错或者是抛出了异常 解决方法:查看一下对应的代码是不是有问题. 502 502即 Bad Gateway网关(这里的网关是指CGI,即通用网关接口,从名字就 ...

  7. 如何下载android官网Lib包

    例如:https://dl-ssl.google.com/android/repository/sources-23_r01.zip

  8. photoshop学习目录

    前面的话 前端工程师最基本的工作是切图.photoshop用的6不6,对于工作效率有很大的影响.小火柴将前端工程师需要掌握的photoshop的知识和技能进行了梳理和归纳,总结成以下目录 目录 前端工 ...

  9. Spring AOP AspectJ Pointcut Expressions With Examples--转

    原文地址:http://howtodoinjava.com/spring/spring-aop/writing-spring-aop-aspectj-pointcut-expressions-with ...

  10. Theano入门神经网络(二) 实现一个XOR门

    与非门的图片如下 示意图 详细解释: 1 定义变量的代码,包括了输入.权值.输出等.其中激活函数采用的是sigmod函数 # -*- coding: utf-8 -*- __author__ = 'A ...