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

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


配置.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


千巷猫影
浏览 547回答 3
3回答

明月笑刀无情

import jsondef 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此外,我们无法知道ConfigBuilderor会发生什么builder.parse_config,因为我们无法访问该代码,所以很抱歉没有考虑您的示例

幕布斯7119047

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 jsondata = json.load(open("config.json"))

慕运维8079593

使用lambdawithmap获取仅包含组织名称的数组>>> list(map(lambda i:i['displayName'],x['organisations']))>>> ['org1', 'org2', 'org3']如果你想json从文件中读取数据,dictionary你可以按如下方式实现。import jsonwith open('config.json') as json_file:    data = json.load(json_file)    org_array = list(map(lambda i:i['displayName'],data['organisations']))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python