tgcloud tgcloud - 26 days ago 7
JSON Question

Unable to fetch key from nested dict

I got below output from Openstack nova API.

{
"u'zoneState": {
"u'available": True
},
"u'hosts": {
"u'compute-1": {
"u'nova-compute": {
"u'available": True,
"u'active": True,
"u'updated_at":
"u'2017-09-26T10":
"04": 49.000000'
}
},
"u'compute-2": {
"u'nova-compute": {
"u'available": True,
"u'active": True,
"u'updated_at":
"u'2017-09-26T10":
"04": 48.000000'
}
}
},
"u'zoneName": u'nova'
}


I am writing python script to get the compute node details in the Availability Zone.

I am able to get the host name, however i am trying to fetch hosts status
"u'available": True,
and
"u'active": True,
, but i and not able to get the keys form dict.

any help would be appreciated.

Answer Source

try this:

for host_key in d["u'hosts"].keys():
    for key in d["u'hosts"][host_key]:
        print d["u'hosts"][host_key][key].get("u'active")

this will print your desired value