Py学习  »  Python

python:从JSON中提取所有特定的子键

Asher • 3 年前 • 1259 次点击  

如果我有如下类似的JSON:

"children": [
        {
            "firstName": "Alice",
            "age": 6
        },
        {
            "firstName": "Bob",
            "age": 8
        }
        {
            "firstName": "Candice",
            "age": 4
        }
    ]

我想要一个包含所有名字值的数组,我该如何用python获取它们?

我尝试过以下方法,但我的数据集较大(40000行),重复它是不切实际的:

children = JSON

firstNames = []

firstNames.append(json.loads(children.text)['children'][0]['firstName'])
firstNames.append(json.loads(children.text)['children'][1]['firstName'])
firstNames.append(json.loads(children.text)['children'][2]['firstName'])

我已经考虑过使用for循环来替换这些数字,但不知道该怎么做。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131797
 
1259 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Tim Roberts
Reply   •   1 楼
Tim Roberts    3 年前

应该清楚地知道如何扩展现有资源。看在上帝的份上,不要多次重复JSON加载。

data = json.loads(children.text)
firstNames = [k['firstname'] for k in data['children']]
nad2000
Reply   •   2 楼
nad2000    3 年前

@asher,如果只运行一次反序列化,可以显著提高性能。要收集姓名,您可以使用列表:

doc = json.loads(children.text)
firstNames = [child["firstname"] for child in doc["children"]]