Home > Software engineering >  Extract JSON Value From Nested List
Extract JSON Value From Nested List

Time:12-28

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?

CodePudding user response:

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"])

CodePudding user response:

Assuming that each entry in the ratings list has a source and a value, and that each rating has a unique source, you can do the following:

# Generate a new list, with any ratings that aren't from Rotten Tomatoes removed.
rotten_tomatoes_ratings = filter(lambda x: x['source'] == 'Rotten Tomatoes', omdb_media['ratings'])

# Only execute the following code if there exists a rating from Rotten Tomatoes.
if rotten_tomatoes_ratings:
   [rating] = rotten_tomatoes_ratings
   # Do stuff with rating...

CodePudding user response:

You can just ask for the next() rating where the source is "Rotten Tomatoes". The final None in this is the result if not sources match, this can be any default value you want:

source = 'Rotten Tomatoes'

rt = next((rating['value'] 
      for rating in d['ratings']
      if rating['source'] == source), None)

print(rt)
# 98%
  • Related