Python:从json文件中获取特定键的所有值

时间:2021-07-19 09:39:05

标签: python json

我正在从文件中获取 json 数据:

 "students": [
     {
        "name" : "ben",
        "age" : 15
     },
     {
        "name" : "sam",
        "age" : 14
     }
  ]
}

这是我的初始代码:

def get_names():
  students = open('students.json')
  data = json.load(students)

我想获取所有名字的值

[ben,sam]

4 个答案:

答案 0 :(得分:1)

您需要从 students 列表中提取名称。

data = {"students": [
     {
        "name" : "ben",
        "age" : 15
     },
     {
        "name" : "sam",
        "age" : 14
     }
  ]
       }

names = [each_student['name'] for each_student in data['students']]

print(names) #['ben', 'sam']

答案 1 :(得分:0)

尝试使用列表推导式:

>>> [dct['name'] for dct in data['students']]
['ben', 'sam']
>>> 

答案 2 :(得分:0)

import json
with open('./students.json', 'r') as students_file:
    students_content = json.load(students_file)
print([student['name'] for student in students_content['students']]) # ['ben', 'sam']

答案 3 :(得分:0)

来自 docs 的 JSON 加载函数:

<块引用>

将 fp(支持 .read() 的文本文件或包含 JSON 文档的二进制文件)反序列化为 Python 对象...

students.json 中的 JSON 文件如下所示:

{
    "students": [
        {
        "name" : "ben",
        "age" : 15
        },
        {
        "name" : "sam",
        "age" : 14
        }
    ]
}

然后可以使用 JSON 加载函数将文件中的这个 JSON 对象反序列化为 Python 字典:

import json

# use with context manager to ensure the file closes properly
with open('students.json', 'rb')as students_fp:
    data = json.load(students_fp)

print(type(data))  # dict i.e. a Python dictionary

# list comprehension to take the name of each student
names = [student['name'] for student in data['students']]

名称现在包含所需的内容:

["ben", "sam"]