【问题标题】:Return nested json string in Python在 Python 中返回嵌套的 json 字符串
【发布时间】: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

【问题讨论】:

    标签: python json loops


    【解决方案1】:

    有两个列表需要循环,首先是结果,然后是图像。你也忘了"gif"

        for result in images["results"]:
            for image in result["media"]:
                print(image["gif"]["preview"])
    

    【讨论】:

    • 我仍然得到同样的错误:TypeError: list indices must be integers or slices, not str
    • 我修改了我的答案。试试新代码。
    猜你喜欢
    • 2013-11-05
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多