Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

python - TypeError: the JSON object must be str, not '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)

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')

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.

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

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...