How to parse json in Python with dynamic key names?

advertisements

I am trying to pull name from the below JSON. The problem I am having is the host name in the JSON is dynamic so I don't know how to dig below that layer if that makes sense. So 'ip-10-12-68-170.b2c.test.com' has a different ip for each block of json.

{
    "host" : {
        "ip-10-12-68-170.b2c.test.com" : {
            "environment" : {
                "testing1" : {
                    "ip" : "ip-10-12-68-170",
                    "name" : "testing",
                    "env.root" : "/",
                    "host" : "ip-10-12-68-170.b2c.test.com",
                    "sin" : "sin.80",
                    "env.description" : "Content Author Preview"
                }
            }
        },
        "ip-10-12-108.27.b2c.test.com" : {
            "environment" : {
                    "esbqav" : {
                    "ip" : "ip-10-12-108.27",
                    "name" : "espv",
                    "env.root" : "/",
                    "host" : "ip-10-12-108.27.b2c.test.com",
                    "sin" : "sin.0",
                    "env.description" : "QA"
                }
            }
        }
    }
}

How do I grab name from this example?


You can iterate over a dict by calling its .items() member. That way, you don't need to know beforehand what the keys are.

json= {
   "host" : {
      "ip-10-12-68-170.b2c.test.com" : {
         "environment" : {
            "testing1" : {
               "ip" : "ip-10-12-68-170",
               "name" : "testing",
               "env.root" : "/",
               "host" : "ip-10-12-68-170.b2c.test.com",
               "sin" : "sin.80",
               "env.description" : "Content Author Preview"
            }
         }
      },
      "ip-10-12-108.27.b2c.test.com" : {
         "environment" : {
            "esbqav" : {
               "ip" : "ip-10-12-108.27",
               "name" : "espv",
               "env.root" : "/",
               "host" : "ip-10-12-108.27.b2c.test.com",
               "sin" : "sin.0",
               "env.description" : "QA"
            }
         }
      }
   }
}
for ip, ip_dict in json['host'].items():
    for hostname, hostname_dict in ip_dict['environment'].items():
        name = hostname_dict['name']
        print (ip, hostname, name)

The following code is equivalent, but iterates over just the keys and not the key,value pairs:

for ip in json['host']:
    for hostname in json['host'][ip]['environment']:
        name = json['host'][ip]['environment'][hostname]['name']
        print (ip, hostname, name)