【发布时间】:2022-01-24 15:03:27
【问题描述】:
我正在尝试在 Python 中返回并存储一个嵌套的 JSON 字符串,我打算用它来从我的程序中的 URL 字符串中提供图像。 JSON 有效负载是这样的:
{
"results": [{
"id": "Some ID",
"title": "Some Title",
"content_description": "Some Description",
"media": [{
"gif": {
"url": "https://somemediasite.com/image.gif",
"dims": [
212,
256
],
"preview": "https://somemediasite.com/imagePreview.gif",
"size": 484133
}
}
]
}
]
}
我希望我的程序在运行时返回“url”字符串,但我无法弄清楚如何。这是我所拥有的:
apikey = "myApiKey"
lmt = 1
search_term = aValuePassedFromAnotherMethod
r = requests.get(
"https://somemediasite.com/random?q=%s&key=%s&limit=%s" % (search_term, apikey, lmt))
if r.status_code == 200:
images = json.loads(r.content)
for image in images["results"]["media"]:
print(images.get('preview'))
运行它会给我错误 TypeError: list indices must be integers or slices, not str
【问题讨论】: