Home > Software engineering >  Return nested json string in Python
Return nested json string in Python

Time:12-24

I'm trying to return and store a nested JSON string in Python which I intend to use to serve the image from the URL string in my program. The JSON payload is this:

{
"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
                        }
                    }
                    ]
            }
    ]
}

I want my program to return the "url" string when it runs but I'm having trouble figuring out how. Here is what I've got:

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'))

Running it gives me the error TypeError: list indices must be integers or slices, not str

CodePudding user response:

There are two lists to loop over, first the results then the images. You also forgot "gif".

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