从JSON中获取多个字段 [Python]

-1 投票
2 回答
1309 浏览
提问于 2025-04-18 14:57

我有一些JSON文件,里面的结构如下所示:

{
    "paragraphs": [
        "Fake anti-virus software that infect PCs with malicious code are a growing threat, according to a study by Google.", 
        "Its analysis of 240m web pages over 13 months showed that fake anti-virus programs accounted for 15% of all malicious software.", 
        "Scammers trick people into downloading programs by convincing them that their PC is infected with a virus.", 
    ], 
    "description": "Google has found ...", 
    "title": "Google warning on fake anti-virus software"
},

我需要遍历这些文件,从多个类似的实例中提取所有的标题字段,并把它们存储到一个新的列表里。有没有人能帮我在Python中怎么做?如果你能告诉我怎么处理段落字段就更好了,因为那里有多个条目,而不是只有一个。

2 个回答

0

我做了类似这样的事情:

with open("out.json") as j:
    json_data = j.read()
    data = json.loads(json_data)

for x in range(0,len(data)):
    print data[x]['title']

而且它成功了。现在唯一的问题是,怎么获取每一个段落,因为每个段落部分都有多个实例,如上所示。

1
  1. 使用 json 模块,把你的json文件解析成嵌套的字典和列表结构。
  2. 使用 列表推导式 来提取你的描述,比如:

    titles = [x['title'] for x in parsed_json]
    

撰写回答