【问题标题】:Extract JSON Value From Nested List从嵌套列表中提取 JSON 值
【发布时间】:2021-12-27 21:08:38
【问题描述】:

我正在使用 OMDb API 通过 Python 提取电影/电视节目数据。我正在尝试从以下 JSON 中获取 IMDB、烂番茄和 Metacritic 评级。

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

我想要 Rotten Tomatoes 来源的嵌套分级列表中的“98%”值。我怎样才能得到它而不是使用像omdb_media['ratings'][1]['Value'] 这样的东西?烂番茄并不总是有条目,我也不能保证顺序,因为可能没有 IMDB 或 Metacritic 的条目,但烂番茄有一个条目,所以它的索引发生了变化。

理想情况下,我希望能够通过 JSON 进行搜索,并通过搜索“烂番茄”使其获得该值。

这可能吗?我该怎么做呢?

【问题讨论】:

  • for sv in omdb_media['ratings'] 是你想要的循环,这应该足以让你开始。你需要添加一个if 语句来检查source 是什么
  • 与您的想法相反,StackOverflow 不是免费的编码服务。您应该发送honest attempt at the solution,然后然后仅在遇到问题时询问具体问题。

标签: python json omdbapi


【解决方案1】:
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"])

【讨论】:

  • 谢谢!这正是我想要做的,我只是不知道如何将它放入代码中。
【解决方案2】:

假设ratings 列表中的每个条目都有一个来源和一个值,并且每个评分都有一个唯一的来源,您可以执行以下操作:

# 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...

【讨论】:

    【解决方案3】:

    您可以只要求next() 评级,其中source"Rotten Tomatoes"。如果源不匹配,最后的None 是结果,这可以是您想要的任何默认值:

    source = 'Rotten Tomatoes'
    
    rt = next((rating['value'] 
          for rating in d['ratings']
          if rating['source'] == source), None)
    
    print(rt)
    # 98%
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-24
      • 2014-08-20
      • 2021-08-26
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      相关资源
      最近更新 更多