如何对此实体进行序列化/反序列化?

时间:2015-02-06 20:57:02

标签: python json python-2.7

下面的代码定义了用于转换字段值的字典。读取数据,根据此字典转换一些值,并写入表。它按原样工作。问题是,我现在想将此配置移到.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并尽量减少对代码的更改?

3 个答案:

答案 0 :(得分: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']}}

如果不是按原样使用。

答案 1 :(得分:0)

如果你知道你的密钥是什么类型的数据,那么密钥上的简单int就足够了:

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

答案 2 :(得分: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)