Python 类型错误:JSON 对象必须是 str,而不是 'bytes'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42683478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: the JSON object must be str, not 'bytes'
提问by FunnyChef
I have the following, very basic code that throws; TypeError: the JSON object must be str, not 'bytes'
我有以下非常基本的代码抛出; 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)
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')
我尝试将 decode 设置为 Data 变量,如下所示,但它引发了相同的错误; jData = json.loads(myResponse.content).decode('utf-8')
Any suggestions?
有什么建议?
回答by Neil
json.loads(myResponse.content.decode('utf-8'))
You just put it in the wrong order, innocent mistake.
你只是把它放在错误的顺序,无辜的错误。
(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.
(深度回答)。正如 wim 礼貌地指出的那样,在极少数情况下,他们可以选择 UTF-16 或 UTF-32。这些情况将不那么常见,因为开发人员会在这种情况下有意识地决定丢弃宝贵的带宽。因此,如果遇到编码问题,可以将 utf-8 更改为 16、32 等。
There are a couple of solutions for this. You could use request's built-in .json()
function:
对此有几种解决方案。您可以使用请求的内置.json()
函数:
myResponse.json()
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.
或者,您可以选择通过chardet
. Chardet 是一个基于研究开发的库。该库有一个功能:detect
. Detect 可以检测最常见的编码,然后使用它们对您的字符串进行编码。
import chardet
json.loads(myResponse.content.decode(chardet.detect(myResponse.content)["encoding"]))
回答by wim
Let requests decode it for you:
让请求为您解码:
data = response.json()
This will check headers (Content-Type) and response encoding, auto-detecting how to decode the content correctly.
这将检查标题(内容类型)和响应编码,自动检测如何正确解码内容。
回答by Suraj Shrestha
python3.6+ does this automatically.so your code shouldn't return error in python3.6+
python3.6+ 会自动执行此操作。因此您的代码不应在 python3.6+ 中返回错误