简体   繁体   English

python 从列表中获取 json 个值

[英]python getting json values from list

I have some json data similar to this...我有一些与此类似的 json 数据......

    {
        "people": [
            {
                "name": "billy",
                "age": "12"
                 ...
                 ...
            },
            {
                "name": "karl",
                "age": "31"
                 ...
                 ...
            },
            ...
            ...
        ]
    }

At the moment I can do this to get a entry from the people list...目前我可以这样做以从人员列表中获取条目......

wantedPerson = "karl"

for person in people:
    if person['name'] == wantedPerson:
        * I have the persons entry *
        break

Is there a better way of doing this?有更好的方法吗? Something similar to how we can .get('key') ?类似于我们如何.get('key')东西? Thanks, Chris谢谢,克里斯

Assuming you load that json data using the standard library for it, you're fairly close to optimal, perhaps you were looking for something like this:假设您使用标准库加载 json 数据,那么您已经非常接近最佳状态,也许您正在寻找这样的东西:

from json import loads

text = '{"people": [{"name": "billy", "age": "12"}, {"name": "karl", "age": "31"}]}'

data = loads(text)

people = [p for p in data['people'] if p['name'] == 'karl']

If you frequently need to access this data, you might just do something like this:如果您经常需要访问这些数据,您可以这样做:

all_people = {p['name']: p for p in data['people']}

print(all_people['karl'])

That is, all_people becomes a dictionary that uses the name as a key, so you can access any person in it quickly by accessing them by name.也就是说, all_people变成了一个以姓名为键的字典,因此您可以通过按姓名访问他们来快速访问其中的任何人。 This assumes however that there are no duplicate names in your data.但是,这假设您的数据中没有重复的名称。

First, there's no problem with your current 'naive' approach - it's clear and efficient since you can't find the value you're looking for without scanning the list.首先,您当前的“天真”方法没有问题 - 它清晰有效,因为如果不扫描列表就无法找到您正在寻找的值。

It seems that you refer to better as shorter, so if you want a one-liner solution, consider the following:似乎您指的是更短的更好,因此如果您想要一个单线解决方案,请考虑以下事项:

next((person for person in people if person.name == wantedPerson), None)

It gets the first person in the list that has the required name or None if no such person was found.它获取列表中第一个具有所需名称的人,如果没有找到这样的人,则获取None

similarly相似地

ps =  {
        "people": [
            {
                "name": "billy",
                "age": "12"
    
            },
            {
                "name": "karl",
                "age": "31"
            },
        ]
    }

print([x for x in ps['people'] if 'karl' in x.values()])

For possible alternatives or details see eg # Get key by value in dictionary有关可能的替代方案或详细信息,请参见例如 # Get key by value in dictionary

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

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