如何从json数组中获取第一个元素的数组

2024-09-28 21:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个config.json文件,其中包含一系列组织:

config.json

{
    "organisations": [
        { "displayName" : "org1", "bucketName" : "org1_bucket" },
        { "displayName" : "org2", "bucketName" : "org2_bucket" },
        { "displayName" : "org3", "bucketName" : "org3_bucket" }
    ]
}

如何获取所有组织名称的数组

这就是我尝试过的:

from python_json_config import ConfigBuilder

def read_config():
    builder = ConfigBuilder()
    org_array = builder.parse_config('config.json')

    # return all firstNames in org_array

Tags: 文件org名称configjsonbucketbuilderarray
3条回答
import json

def read_config():
    display_names = []
    with open('yourfilename.json', 'r', encoding="utf-8") as file:
        orgs = json.load(file)
        display_names = [ o["displayName"] for o in orgs["organizations"] ]
    return display_names

此外,我们无法知道ConfigBuilderbuilder.parse_config会发生什么,因为我们无法访问该代码,所以很抱歉没有考虑您的示例

a = {
    "organisations": [
        { "displayName" : "org1", "bucketName" : "org1_bucket" },
        { "displayName" : "org2", "bucketName" : "org2_bucket" },
        { "displayName" : "org3", "bucketName" : "org3_bucket" }
    ]
}

print([i["displayName"] for i in a["organisations"]])

输出:

['org1', 'org2', 'org3']

使用列表理解,这很简单。以读取json文件

import json
data = json.load(open("config.json"))

使用lambdamap来获取仅组织名称的数组

>>> list(map(lambda i:i['displayName'],x['organisations']))
>>> ['org1', 'org2', 'org3']

如果您想将json数据从文件读入dictionary,可以通过以下方式实现

import json
with open('config.json') as json_file:
    data = json.load(json_file)
    org_array = list(map(lambda i:i['displayName'],data['organisations']))

相关问题 更多 >