[英]Parsing JSON with Python TypeError: list indices must be integers or slices, not str
i read about 10 to 12 answer but nothing help me.我读了大约 10 到 12 个答案,但没有任何帮助。
i wanna print the url shows in picute click to see this is my code :我想打印显示在 picute click 中的 url以查看这是我的代码:
> 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'])
but i get this error :但我收到此错误:
TypeError: list indices must be integers or slices, not str
edit1:编辑1:
i saw someone say put [0] in you code.
我看到有人说把 [0] 放在你的代码中。 if i change
如果我改变
print (data['data']['0']['image']['standard_resolution']['url'])
to this
对此
print (data[0]['data']['0']['image']['standard_resolution']['url']) i will get new error -> KeyError: 0
edit2:编辑2:
and if i change
如果我改变
data = simplejson.load(response)
to this
对此
pdata = simplejson.loads(response)
i will get new error ->
我会得到新的错误 ->
aise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not HTTPResponse
aise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not HTTPResponse
The advice is to use an integer, not to add an extra two lookups.建议是使用整数,而不是添加额外的两次查找。
print(data['data'][0]['images']['standard_resolution']['url'])
Note, that data has images
not image
.请注意,数据具有
images
而不是image
。
(Also, there's no reason to import the json library as simplejson. simplejson was a library that was popular before json was included in the standard library; but that was added in version 2.6 and we're on 3.7 now. Just import json and use it.) (另外,没有理由将 json 库作为 simplejson 导入。simplejson 是一个在 json 被包含在标准库中之前流行的库;但它是在2.6版本中添加的,我们现在是 3.7。只需导入 json 并使用它。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.