亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從 json 數組中獲取第一個元素的數組

如何從 json 數組中獲取第一個元素的數組

千巷貓影 2023-03-08 17:29:23
我有一個 config.json 文件,其中包含一組組織:配置.json{    "organisations": [        { "displayName" : "org1", "bucketName" : "org1_bucket" },        { "displayName" : "org2", "bucketName" : "org2_bucket" },        { "displayName" : "org3", "bucketName" : "org3_bucket" }    ]}如何獲得所有組織名稱的數組?這是我試過的:from python_json_config import ConfigBuilderdef read_config():    builder = ConfigBuilder()    org_array = builder.parse_config('config.json')    # return all firstNames in org_array
查看完整描述

3 回答

?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

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

此外,我們無法知道ConfigBuilderor會發生什么builder.parse_config,因為我們無法訪問該代碼,所以很抱歉沒有考慮您的示例


查看完整回答
反對 回復 2023-03-08
?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

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"))


查看完整回答
反對 回復 2023-03-08
?
慕運維8079593

TA貢獻1876條經驗 獲得超5個贊

使用lambdawithmap獲取僅包含組織名稱的數組


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


查看完整回答
反對 回復 2023-03-08
  • 3 回答
  • 0 關注
  • 589 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號