简体   繁体   English

如何使该实体序列化/反序列化?

[英]How do make serialize / deserialize this entity?

The code below defines a dictionary used to transform field values. 下面的代码定义了一个用于转换字段值的字典。 Data is read, some of the values are transformed based on this dictionary, and written to a table. 读取数据,一些值根据此字典进行转换,然后写入表中。 It works as-is. 它按原样工作。 The problem, I now want to move this configuration outside the .py file into a JSON configuration file. 问题是,我现在想将此配置从.py文件外移到JSON配置文件中。

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

According to jsonlint.com, in order for the above value being assigned to lookups to be valid JSON, I must quote the 11 and 10 keys. 根据jsonlint.com,为了将上述值分配给lookups为有效的JSON,我必须引用1110键。 Doing so breaks my Python code and displays TypeError: list indices must be integers, not str . 这样做会破坏我的Python代码并显示TypeError: list indices must be integers, not str

How do I create valid JSON and minimize changes to my code? 如何创建有效的JSON并最小化对代码的更改?

If you want to dump it to a json file: 如果要将其转储到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']}}

If you need keys as ints you can loop and cast as ints or use pickle : 如果您需要将键作为整数,则可以循环并转换为整数或使用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']}}

If not just use as is. 如果不按原样使用。

If you know what type of data your keys are, a simple int on the keys would suffice: 如果您知道密钥是什么类型的数据,则只需对密钥进行简单的int就可以:

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

You can extend json.decoder and convert all keys to int when it's possible. 您可以扩展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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM