我試圖在 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'))
運行它給我錯誤型別錯誤:串列索引必須是整數或切片,而不是 str
uj5u.com熱心網友回復:
有兩個串列可以回圈,首先是結果,然后是影像。你也忘記了"gif"。
for result in images["results"]:
for image in result["media"]:
print(image["gif"]["preview"])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/391578.html
