pythonjsonomdbapi

Extract JSON Value From Nested List


I am using the OMDb API to pull movie/tv show data using Python. I am trying to get the IMDB, Rotten Tomatoes, and Metacritic ratings from the following JSON.

{
    "title": "One Hundred and One Dalmatians",
    "year": "1961",
    "rated": "G",
    "ratings": [
        {
            "source": "Internet Movie Database",
            "value": "7.2/10"
        },
        {
            "source": "Rotten Tomatoes",
            "value": "98%"
        },
        {
            "source": "Metacritic",
            "value": "83/100"
        }
    ],
    "response": "True"
}

I want the value of "98%" from the nested list of ratings for the Rotten Tomatoes source. How can I get that instead of using something like omdb_media['ratings'][1]['Value']? There isn't always an entry for Rotten Tomatoes and I also can't guarantee the order since there may not be an entry for IMDB or Metacritic, but one for Rotten Tomatoes, so its index changes.

Ideally, I'd like to be able to search through the JSON and have it get that value by being able to search for "Rotten Tomatoes".

Is this possible? How would I go about doing it?


Solution

  • json ={
        "title": "One Hundred and One Dalmatians",
        "year": "1961",
        "rated": "G",
        "ratings": [
            {
                "source": "Internet Movie Database",
                "value": "7.2/10"
            },
            {
                "source": "Rotten Tomatoes",
                "value": "98%"
            },
            {
                "source": "Metacritic",
                "value": "83/100"
            }
        ],
        "response": "True"
    }
    
    for rating in json["ratings"] :
        if(rating["source"] == "Rotten Tomatoes") :
            print(rating["value"])