UnicodeDecodeError:'utf8'编解码器在迭代json时无法解码字节



我是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
},

您的程序在解释 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

最新更新