我是python的初学者。我试图在我的代码中使用json.loads()来迭代从API返回的json对象。
以下是我得到的错误:
Traceback (most recent call last):
File "/Users/Saket/Downloads/Telegram Desktop/update_trbble (2).py", line 209, in <module>
today_trbbles=json.loads(open_discovery_api)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd8 in position 36: unexpected end of data
logout
我查了几篇文章并尝试使用.encode('utf-8')并使用unicode()方法转换为unicode。这些也没有用。
示例数据:
status: 0,
message: "success",
results: {
totalTime: "3 ms",
queryTime: "0 ms",
status: 0,
cursor: "AoJ/spqIs9ICPwU4YzcyNWFlZi1hNjM1LTRiNzEtYjM1Ni02MWQ2MWFlMGQwZWU=",
numFound: 523,
size: 30,
songss: [
{
albumArt: "https://i.scdn.co/image/233728c2073337d67309fd205c6cc028e831d857",
artist: "Arty, Nadia Ali & BT",
docSource: [
"CACHE"
],
commentCount: 0,
createdBy: "wiredmau5",
createdTime: "Fri Jan 22 15:07:45 UTC 2016",
createdUTS: 1453475265411,
createdUserId: "ae186330-5fa5-469c-b1cc-8f3d3b61e538",
downVoteCount: 0,
favouriteCount: 0,
flag1Count: 0,
falg2Count: 0,
flag3Count: 0,
flag4Count: 0,
flag5Count: 0,
flag6Count: 0,
genre: [
"Trance"
],
genrePriority: 0,
hour: 0,
language: "english",
languagePriority: 0,
likeCount: 0,
minute: 0,
modifiedTime: {
time: 1453475748201,
minutes: 15,
seconds: 48,
hours: 15,
month: 0,
year: 116,
timezoneOffset: 0,
day: 5,
date: 22
},
答案 0 :(得分:0)
您的程序在解释API请求输出的编码时遇到问题。首先,确保导入了json和urllib.request。然后,您需要打开API URL,在这种情况下,我将输出设置为byte_Obj。然后,您将使用.read()和.decode()函数将信息转换为ascii文本。然后,要使索引整数,您将使用导入的json包中的.load()函数。希望这有帮助!
import json
import urllib.request
byte_Obj = urllib.request.urlopen("API URL Here") #urllib is used to open the URL of the API provided
json_string = byte_Obj.read().decode("ascii", "ignore") #to decode output into ascii text
info = json.loads(json_string) #final info with indices as integers