2015-02-06 83 views
1

下面的代碼定義了一個用於轉換字段值的字典。數據被讀取,一些值基於這個字典被轉換,並被寫入到一個表中。它按原樣工作。這個問題,我現在想將這個配置移到.py文件之外的一個JSON配置文件中。如何使這個實體序列化/反序列化?

lookups = { 
    11: { 
     "ST1": ["ABC"], 
     "UNK01": ["125", "ACD"], 
     "A": ["52"], 
     "B": ["91"], 
     "C": ["92"], 
     "D": ["95"] 
     }, 
    10: { 
     "XYZ01": ["91"], 
     "XYZ02": ["83"], 
     "XYZ03": ["27"] 
     } 
} 

根據jsonlint.com,爲了上述值被分配給lookups是有效的JSON,我必須報1110密鑰。這樣做會破壞我的Python代碼並顯示TypeError: list indices must be integers, not str

如何創建有效的JSON並儘量減少對代碼的更改?

回答

0

如果你知道你的鑰匙是什麼類型的數據,在按鍵上簡單int就足夠了:

dictionary_from_json = json.loads(dumped) 
newdict = {} 
for key, val in dictionary_from_json: 
    newdict[int(key)] = val 
1

如果你想將它轉儲到JSON文件:

import json 

with open("config.json","w") as f: 
    json.dump(lookups, f) # dump dict to file 

with open("config.json") as f: 
    s = json.load(f) # load dict from file 
print(s) 
{'11': {'ST1': ['ABC'], 'A': ['52'], 'D': ['95'], 'UNK01': ['125', 'ACD'], 'B': ['91'], 'C': ['92']}, '10': {'XYZ01': ['91'], 'XYZ03': ['27'], 'XYZ02': ['83']}} 

如果您需要密鑰作爲整數,您可以循環並投射爲整數或使用pickle

import pickle 
with open("in.pkl","wb") as f: 
    pickle.dump(lookups, f) 

with open("in.pkl","rb") as f: 
    s = pickle.load(f) 
print(s) 
{10: {'XYZ03': ['27'], 'XYZ01': ['91'], 'XYZ02': ['83']}, 11: {'UNK01': ['125', 'ACD'], 'B': ['91'], 'D': ['95'], 'ST1': ['ABC'], 'C': ['92'], 'A': ['52']}} 

如果不是按原樣使用。

0

您可以擴展json.decoder並在可能的情況下將所有的鍵轉換爲int。

import json 
class Json(json.JSONDecoder): 
    def decode(self,json_string): 
     default_obj = super(Json,self).decode(json_string) 
     new_obj = self._rec_serial(default_obj) 
     return new_obj 

    def _rec_serial(self,default): 
     new_dict = {} 
     for key,value in default.items(): 
      is_dict = isinstance(value,dict) 
      value = self._rec_serial(value) if is_dict else value 
      try: 
       new_dict[int(key)] = value 
      except ValueError: 
       new_dict[key] = value 
     return new_dict 

json2= Json() 
d = json2.decode(dumped)