2016-04-07 85 views
-1

我想從下面的JSON中拉name。我遇到的問題是JSON中的主機名是動態的,所以我不知道如何在該層下挖掘,如果這是有道理的。因此'ip-10-12-68-170.b2c.test.com'對每個json塊都有不同的ip。如何使用動態鍵名解析Python中的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" 
       } 
      } 
     } 
    } 
} 

如何從此示例中抓取name

+0

要清楚的是,您的問題中的代碼示例是JSON字符串還是Python程序片段? –

回答

0

您可以通過調用其.items()成員來遍歷dict。這樣,你不需要事先知道鑰匙是什麼。

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) 

以下代碼是等效的,但在剛剛鑰匙迭代並不是關鍵,值對:

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

它使用字典values()items()方法,因爲該結構是可能在這個例子中。

import json 

json_string = """ 
{ 
    "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" 
      } 
     } 
    } 
    } 
} 
""" 

json_data = json.loads(json_string) 

for host in json_data.values(): 
    for hostname in host.values(): 
     environment = hostname.get('environment') 

     for env in environment.values(): 
      name = env.get('name') 
      print name