TypeError:JSON对象必须为str,而不是"bytes" [英] TypeError: the JSON object must be str, not 'bytes'

查看:85
本文介绍了TypeError:JSON对象必须为str,而不是"bytes"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下非常基本的代码会抛出; TypeError:JSON对象必须为str,而不是"bytes"

I have the following, very basic code that throws; TypeError: the JSON object must be str, not 'bytes'

import requests
import json

url = 'my url'
user = 'my user'
pwd = 'my password'

response = requests.get(url, auth=(user, pwd))

if(myResponse.ok):
    Data = json.loads(myResponse.content)

我尝试将解码设置为Data变量,如下所示,但它会引发相同的错误; jData = json.loads(myResponse.content).decode('utf-8')

I try to set decode to the Data variable, as follows but it throws the same error; jData = json.loads(myResponse.content).decode('utf-8')

有什么建议吗?

推荐答案

json.loads(myResponse.content.decode('utf-8'))

您只是按错误的顺序放置它,是无辜的错误.

You just put it in the wrong order, innocent mistake.

(深入解答).正如wim所礼貌地指出的那样,在极少数情况下,他们可以选择UTF-16或UTF-32.在这种情况下,对于开发人员而言,这种情况将不那么常见,在这种情况下,他们将有意识地决定放弃宝贵的带宽.因此,如果遇到编码问题,可以将utf-8更改为16、32等.

(In-depth answer). As courteously pointed out by wim, in some rare cases, they could opt for UTF-16 or UTF-32. These cases will be less common as the developers, in that scenario would be consciously deciding to throw away valuable bandwidth. So, if you run into encoding issues, you can change utf-8 to 16, 32, etc.

有两种解决方案.您可以使用请求的内置.json()函数:

There are a couple of solutions for this. You could use request's built-in .json() function:

myResponse.json()

或者,您可以选择通过chardet进行字符检测. Chardet是基于研究开发的图书馆.该库具有一个功能:detect.检测可以检测到最常见的编码,然后使用它们来对您的字符串进行编码.

Or, you could opt for character detection via chardet. Chardet is a library developed based on a study. The library has one function: detect. Detect can detect most common encodings and then use them to encode your string with.

import chardet
json.loads(myResponse.content.decode(chardet.detect(myResponse.content)["encoding"]))

这篇关于TypeError:JSON对象必须为str,而不是"bytes"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆