繁体   English   中英

从 Python 的嵌套列表中提取 JSON 值

[英]Extract JSON Value From Nested List in Python

我正在使用 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 并通过搜索“烂番茄”来获得该值。

这可能吗? 我会怎么做 go

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

假设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...

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

source = 'Rotten Tomatoes'

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

print(rt)
# 98%

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM