如何在python中访问复杂数据结构中的某些元素

2024-04-19 10:10:54 发布

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

我目前正在尝试使用exoscale(一个cloudprovider)提供的API自动化一些东西。当我向exoscale发送特定的API请求时,我得到以下答案:

{
"count": 1,
"virtualmachine": [
    {
        "account": "account@email.com",
        "cpunumber": 1,
        "cpuspeed": 2198,
        "cpuused": "0.22%",
        "created": "2013-12-19T22:28:31+0100",
        "displayname": "vagrant_1387488511",
        "guestosid": "113038d0-a8cd-4d20-92be-ea313f87c3ac",
        "haenable": false,
        "hypervisor": "KVM",
        "id": "8e5fe56d-6d8a-4210-b826-73327b9385dc",
        "keypair": "vagrant",
        "memory": 512,
        "name": "8e5fe56d-6d8a-4210-b826-73327b9385dc",
        "networkkbsread": 10060,
        "networkkbswrite": 5443,
        "nic": [
            {
                "gateway": "185.19.28.1",
                "id": "672bf4f3-8ed0-4581-9b3d-b6cd4c4fe8e6",
                "ipaddress": "185.19.28.148",
                "isdefault": true,
                "macaddress": "06:78:f8:00:00:d1",
                "netmask": "255.255.254.0",
                "networkid": "00304a04-c7ea-4e77-a786-18bc64347bf7",
                "traffictype": "Guest",
                "type": "Shared"
            }
        ],
        "passwordenabled": true,
        "rootdeviceid": 0,
        "rootdevicetype": "Filesystem",
        "securitygroup": [
            {
                "description": "Default Security Group",
                "id": "b87ff34d-abf3-42d3-a097-78075515dd34",
                "name": "default"
            }
        ],
        "serviceofferingid": "71004023-bb72-4a97-b1e9-bc66dfce9470",
        "serviceofferingname": "Micro",
        "state": "Stopped",
        "tags": [],
        "templatedisplaytext": "Linux Ubuntu 12.04 LTS 64-bit 10GB Disk",
        "templateid": "a17b40d6-83e4-4f2a-9ef0-dce6af575789",
        "templatename": "Linux Ubuntu 12.04 LTS 64-bit",
        "zoneid": "1128bd56-b4d9-4ac6-a7b9-c715b187ce11",
        "zonename": "CH-GV2"
    }
]
}

如何在python中访问structure中的“description”元素(在“securitygroup”中),是否有一种方法可以“搜索”特定键并获取返回的值,以便将其存储在变量中


Tags: nameapiidtrueubuntulinuxservicebit
1条回答
网友
1楼 · 发布于 2024-04-19 10:10:54

您可以使用内置模块json

import json
x = json.loads(stringVarHere)["virtualmachine"][0]["securitygroup"][0]["description"]
print(x)

输出:

Default Security Group

相关问题 更多 >