2015-07-21 84 views
0

鑑於從web形式接收以下數據:把一個簡單的字典到字典中嵌套列表

for key in request.form.keys(): 
    print key, request.form.getlist(key) 

group_name [u'myGroup'] 
category [u'social group'] 
creation_date [u'03/07/2013'] 
notes [u'Here are some notes about the group'] 
members[0][name] [u'Adam'] 
members[0][location] [u'London'] 
members[0][dob] [u'01/01/1981'] 
members[1][name] [u'Bruce'] 
members[1][location] [u'Cardiff'] 
members[1][dob] [u'02/02/1982'] 

我怎樣才能把它變成像這樣一本字典?它最終將用作JSON,但由於JSON和字典很容易互換,因此我的目標只是實現以下結構。

event = { 
    group_name : 'myGroup', 
    notes : 'Here are some notes about the group, 
    category : 'social group', 
    creation_date : '03/07/2013', 
    members : [ 
     { 
      name : 'Adam', 
      location : 'London', 
      dob : '01/01/1981' 
     } 
     { 
      name : 'Bruce', 
      location : 'Cardiff', 
      dob : '02/02/1982' 
     } 
    ] 
} 

這是我迄今爲止所管理的。使用下面的列表理解我可以很容易地使普通領域的意識:

event = [ (key, request.form.getlist(key)[0]) for key in request.form.keys() if key[0:7] != "catches" ] 

,但我與成員列表中掙扎。可以有任意數量的成員。我想我需要爲它們單獨創建一個列表,並將其添加到包含非迭代記錄的字典中。我可以得到會員數據是這樣的:

tmp_members = [(key, request.form.getlist(key)) for key in request.form.keys() if key[0:7]=="members"] 

然後我就可以拉出列表索引和字段名:

member_arr = [] 
members_orig = [ (key, request.form.getlist(key)[0]) for key in request.form.keys() if key[0:7] == 

"members" ] 
for i in members_orig: 
    p1 = i[0].index('[') 
    p2 = i[0].index(']') 
    members_index = i[0][p1+1:p2] 
    p1 = i[0].rfind('[') 
    members_field = i[0][p1+1:-1] 

但我怎麼添加這個到我的數據結構。以下內容不起作用,因爲我可能試圖在members[0][name]之前處理members[1][name]

members_arr[int(members_index)] = {members_field : i[1]} 

這似乎很複雜。有沒有一個簡單的方法來做到這一點,如果不是,我怎麼能得到這個工作?

+0

['進口json'](https://docs.python.org/2/library/json.html) – NightShadeQueen

回答

0

以下python函數可用於從平面字典中創建嵌套字典。只需將html表單輸出傳遞給decode()即可。

def get_key_name(str): 
    first_pos = str.find('[') 
    return str[:first_pos] 

def get_subkey_name(str): 
    '''Used with lists of dictionaries only''' 
    first_pos = str.rfind('[') 
    last_pos = str.rfind(']') 
    return str[first_pos:last_pos+1] 

def get_key_index(str): 
    first_pos = str.find('[') 
    last_pos = str.find(']') 
    return str[first_pos:last_pos+1] 

def decode(idic): 
    odic = {} # Initialise an empty dictionary 
    # Scan all the top level keys 
    for key in idic: 
     # Nested entries have [] in their key 
     if '[' in key and ']' in key: 
      if key.rfind('[') == key.find('[') and key.rfind(']') == key.find(']'): 
       print key, 'is a nested list' 
       key_name = get_key_name(key) 
       key_index = int(get_key_index(key).replace('[','',1).replace(']','',1)) 
       # Append can't be used because we may not get the list in the correct order. 
       try: 
        odic[key_name][key_index] = idic[key][0] 
       except KeyError: # List doesn't yet exist 
        odic[key_name] = [None] * (key_index + 1) 
        odic[key_name][key_index] = idic[key][0] 
       except IndexError: # List is too short 
        odic[key_name] = odic[key_name] + ([None] * (key_index - len(odic[key_name]) + 1)) 
        # TO DO: This could be a function 
        odic[key_name][key_index] = idic[key][0] 
      else: 
       key_name = get_key_name(key) 
       key_index = int(get_key_index(key).replace('[','',1).replace(']','',1)) 
       subkey_name = get_subkey_name(key).replace('[','',1).replace(']','',1) 
       try: 
        odic[key_name][key_index][subkey_name] = idic[key][0] 
       except KeyError: # Dictionary doesn't yet exist 
        print "KeyError" 
        # The dictionaries must not be bound to the same object 
        odic[key_name] = [{} for _ in range(key_index+1)] 
        odic[key_name][key_index][subkey_name] = idic[key][0] 
       except IndexError: # List is too short 
        # The dictionaries must not be bound to the same object 
        odic[key_name] = odic[key_name] + [{} for _ in range(key_index - len(odic[key_name]) + 1)] 
        odic[key_name][key_index][subkey_name] = idic[key][0] 
     else: 
      # This can be added to the output dictionary directly 
      print key, 'is a simple key value pair' 
      odic[key] = idic[key][0] 
    return odic 
1

您可以將數據存儲在字典中,然後使用json庫。

import json 
json_data = json.dumps(dict) 
print(json_data) 

這將打印一個json字符串。

退房的json library here

+0

使用'json.dumps()'直接對原始數據或甚至沒有按members_orig」 t將成員分組成一個列表。它只是創建了一個名爲'members [0] [name]',members [1] [name]''的單獨關鍵字。 –

0

是,將其轉換爲一個字典,然後使用json.dumps(),有一些可選參數,格式打印出JSON,你需要:

eventdict = { 
    'group_name': 'myGroup', 
    'notes': 'Here are some notes about the group', 
    'category': 'social group', 
    'creation_date': '03/07/2013', 
    'members': [ 
     {'name': 'Adam', 
     'location': 'London', 
     'dob': '01/01/1981'}, 
     {'name': 'Bruce', 
     'location': 'Cardiff', 
     'dob': '02/02/1982'} 
     ] 
    } 

import json 

print json.dumps(eventdict, indent=4) 

key:value對的順序並不總是一致的,但如果您只是尋找可以通過腳本解析的漂亮外觀的JSON,同時保持可讀性,這應該可以工作。您還可以使用以下字母順序排序鍵:

print json.dumps(eventdict, indent=4, sort_keys=True) 
+0

我的問題實際上是關於如何獲得您在此處顯示的eventdict字典。那麼,我該如何從request.form中的表單數據到我稱爲event的字典或稱爲eventdict的你的字典(它們都是相同的)。我不是在尋找漂亮的JSON,我正在尋找可以加載到MongoDB中的JSON。 –