代码之家  ›  专栏  ›  技术社区  ›  Hooman Bahreini

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

  •  0
  • Hooman Bahreini  · 技术社区  · 6 年前

    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
    
    4 回复  |  直到 6 年前
        1
  •  1
  •   ewen-lbh    6 年前
    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
    

    而且,我们没有办法知道 ConfigBuilder 或 builder.parse_config

        2
  •  1
  •   bigbounty    6 年前
    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"))
    
        3
  •  0
  •   CHINTAN VADGAMA    6 年前

    使用 lambda map 获取仅组织名称的数组

    >>> 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']))