【问题标题】:Parsing JSON with Python TypeError: list indices must be integers or slices, not str使用 Python TypeError 解析 JSON:列表索引必须是整数或切片,而不是 str
【发布时间】:2019-07-11 05:27:28
【问题描述】:

我阅读了大约 10 到 12 个答案,但没有任何帮助。

我想打印图片中显示的网址 click to see 这是我的代码:

> from urllib.request import urlopen 
> import json as simplejson

> link = "https://api.instagram.com/v1/users/self/media/recent/?access_token=2290710571.098b867.5cf99a24896b476982c70c47eb0a0413"

> response = urlopen(link)
> data = simplejson.load(response) 
> print (data['data']['0']['image']['standard_resolution']['url'])

但我收到此错误:

TypeError: list indices must be integers or slices, not str

编辑1:

我看到有人说在你的代码中放入 [0]。 如果我改变了

print (data['data']['0']['image']['standard_resolution']['url'])

到这里

print (data[0]['data']['0']['image']['standard_resolution']['url'])
 i will get new error -> KeyError: 0

编辑2:

如果我改变了

data = simplejson.load(response)

到这里

pdata = simplejson.loads(response)

我会得到新的错误->

aise TypeError(f'JSON对象必须是str, bytes or bytearray, ' TypeError:JSON 对象必须是 str、bytes 或 bytearray,而不是 HTTP响应

【问题讨论】:

  • 试试simplejson.loads(response)
  • 代码中有simplejson.loads(response)...
  • shet...我现在看到了:D。现在会出现新错误
  • raise TypeError(f'JSON对象必须是str, bytes or bytearray, ' TypeError: JSON对象必须是str, bytes or bytearray, not HTTPResponse
  • @Amin 请不要在 cmets 中回答。您的建议不正确,但评论不能被否决。

标签: python json django


【解决方案1】:

建议使用整数,而不是添加额外的两个查找。

print(data['data'][0]['images']['standard_resolution']['url'])

请注意,该数据包含 images 而不是 image。

(另外,没有理由将 json 库导入为 simplejson。simplejson 是一个在 json 包含在标准库中之前很流行的库;但它是在 2.6 版本中添加的,我们'现在重新上 3.7。只需导入 json 并使用它。)

【讨论】:

  • 在你的代码放置后出现新的错误:aise TypeError(f'JSON 对象必须是 str、bytes 或 bytearray,' TypeError: JSON 对象必须是 str、bytes 或 bytearray,而不是 HTTPResponse
  • 因为您遵循了 Amin 的错误建议来使用 loads。不要。
猜你喜欢
  • 2017-11-19
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 2020-11-21
  • 2017-10-08
  • 1970-01-01
相关资源
最近更新 更多