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

我目前正在尝试使用exoscale(一个云提供商)提供的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的结构中访问“描述”元素(在“安全组”中),并且有一种方法可以“搜索”特定键并取回值以将其存储在变量中?

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

您可以使用内置模块json

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

输出:

Default Security Group
本文链接:https://www.f2er.com/3137961.html

大家都在问