【问题标题】:Save Nested Objects to File in Python3在 Python3 中将嵌套对象保存到文件
【发布时间】:2019-01-19 09:46:15
【问题描述】:

如何将这种 Python 对象结构保存到文件中(最好是 JSON)?我怎样才能再次从文件中加载这个结构?

class Nested(object):
    def __init__(self, n):
        self.name = "Nested Object: " + str(n)
        self.state = 3.14159265359

class Nest(object):
    def __init__(self):
        self.x = 1
        self.y = 2
        self.objects = []

tree = []
tree.append(Nest())
tree.append(Nest())
tree.append(Nest())

tree[0].objects.append(Nested(1))
tree[0].objects.append(Nested(2))

tree[1].objects.append(Nested(1))


tree[2].objects.append(Nested(7))
tree[2].objects.append(Nested(8))
tree[2].objects.append(Nested(9))

【问题讨论】:

标签: json python-3.x


【解决方案1】:

感谢对“pickle”的引用,我找到了一个非常简单的解决方案来保存我的对象数组:

泡菜

import pickle

pickle.dump( tree, open( "save.p", "wb" ) )

loaded_objects = pickle.load( open( "save.p", "rb" ) )

jsonpickle

import jsonpickle

frozen = jsonpickle.encode(tree)

with open("save.json", "w") as text_file:
    print(frozen, file=text_file)

file = open("save.json", "r") 
loaded_objects = jsonpickle.decode(file.read())

【讨论】:

    【解决方案2】:

    如果你不想泡菜,也不想使用外部库,你总是可以通过艰难的方式做到这一点:

    import json
    
    class NestEncoder(json.JSONEncoder):
        def default(self, obj):
            entry = dict(obj.__dict__)
            entry['__class__'] = obj.__class__.__name__
            return entry
    
    class NestDecoder(json.JSONDecoder):
        def __init__(self):
            json.JSONDecoder.__init__(self, object_hook=self.dict_to_object)
    
        def dict_to_object(self, dictionary):
            if dictionary.get("__class__") == "Nested":
                obj = Nested.__new__(Nested)
            elif dictionary.get("__class__") == "Nest":
                obj = Nest.__new__(Nest)
            else:
                return dictionary
    
            for key, value in dictionary.items():
                if key != '__class__':
                    setattr(obj, key, value)
            return obj
    
    with open('nest.json', 'w') as file:
        json.dump(tree, file, cls=NestEncoder)
    
    with open('nest.json', 'r') as file:
        tree2 = json.load(file, cls=NestDecoder)
    
    print("Smoke test:")
    print(tree[0].objects[0].name)
    print(tree2[0].objects[0].name)
    

    为类分配属性不必使用setattr() 动态完成,您也可以手动完成。

    这样做可能有很多陷阱,所以要小心。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 2014-02-10
      • 1970-01-01
      • 2019-05-19
      相关资源
      最近更新 更多