2016-09-30 85 views
-3

我有以下JSON,從REST服務返回,我想通過組合父鍵爲每個值生成唯一的名稱。例如。 name+phone+address+city+namename+phone+address+city+population+skilled+male等。如何爲每個JSON值生成唯一名稱

{ 
    "name": "name", 
    "phone": "343444444", 
    "address": { 
    "lat": 23.444, 
    "lng": 34.3322, 
    "city":{ 
     "name": "city name", 
     "population": { 
     "skilled": { 
      "male": 2, 
      "female": 4 
     }, 
     "uneducated": { 
      "male": 20, 
      "femail": 4 
     } 
     } 
    } 
    }, 
    "email": "email", 
    "education": "phd" 
} 

我想合併從JSON樹的父級開始的所有密鑰名稱。

下面是我在做什麼

class TestJson 
    def walk_through(self, json_object): 
     for k, v in json_object.items(): 
      self.x_path = self.x_path + k 
      if type(v) is dict: 
       self.walk_through(v) 
      else: 
       print(self.x_path) 
       self.x_path = "" 

此代碼打印鍵,但僅從目前的父節點開始。我想將所有密鑰合併到json的根目錄。

+0

鍵的順序不保證始終相同。 –

+0

@gre_gor有沒有辦法讓訂單保持不變? – amjad

回答

1

如果忽略namephone鍵,因爲它們不是city nameskilled male祖先和秩序鍵不能保證,你可以遞歸地構建一個扁平的字典。

def walk_through(json_object): 
    d = {} 
    for k, v in json_object.items(): 
     if isinstance(v, dict): 
      v = walk_through(v) 
      for vk, vv in v.items(): 
       d["%s+%s" % (k, vk)] = vv 
     else: 
      d[k] = v 
    return d 

print(json.dumps(walk_through(json_object), indent=2)) 

此打印:

{ 
    "address+city+population+skilled+male": 2, 
    "name": "name", 
    "address+lng": 34.3322, 
    "address+city+name": "city name", 
    "address+lat": 23.444, 
    "address+city+population+uneducated+male": 20, 
    "phone": "343444444", 
    "address+city+population+uneducated+femail": 4, 
    "education": "phd", 
    "email": "email", 
    "address+city+population+skilled+female": 4 
} 

注:這忽略列表一個不會發現裏面他們http://stardict.sourceforge.net/Dictionaries.php下載。

0

如果你要打印你的Python的所有密鑰字典,你可以做到以下幾點:

def print_keys(d): 
    for key, value in d.iteritems(): 
     print key, 
     if isinstance(value, dict): 
      print_keys(value) 
相關問題