简体   繁体   English

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

[英]Python: Get all values of a specific key from json file

Im getting the json data from a file:我从文件中获取 json 数据:

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

here's my initial code:这是我的初始代码:

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

I want to get the values of all names我想获取所有名称的值

[ben,sam]

you need to extract the names from the students list.您需要从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']

Try using a list comprehension:尝试使用列表理解:

>>> [dct['name'] for dct in data['students']]
['ben', 'sam']
>>> 
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']

JSON's load function from the docs :来自文档的JSON 加载函数:

Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object...将 fp(支持 .read() 的文本文件或包含 JSON 文档的二进制文件)反序列化为 Python 对象...

The JSON file in students.json will look like: student.json 中的 JSON 文件如下所示:

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

The JSON load function can then be used to deserialize this JSON object in the file to a Python dictionary:然后可以使用 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']]

Where names now contains the desired:其中名称现在包含所需的:

["ben", "sam"]

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

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