首页 > 解决方案 > 如何用json序列化对象

问题描述

Child和类都Parent继承自 Python 字典:

import json 

class Child(dict):
    def __init__(self, **kwargs):
        super(Child, self).__init__(**kwargs)

class Parent(dict):
    def __init__(self, **kwargs):
        super(Parent, self).__init__(**kwargs)

parent = Parent(child = Child())

print type(parent['child'])

印刷:

<class '__main__.Child'>

使用 执行序列化和反序列化后变成json.dumps常规字典:json.loadsParent['child']

dumped = json.dumps(parent)
loaded = json.loads(dumped)
parent_2 = Parent(**loaded)
print type(parent_2['child'])

印刷:

<type 'dict'>

问题:如何确保在序列化之后parent_2['child']是 的实例Child而不是常规的 Python 字典?

标签: pythonjson

解决方案


loads做一本字典,就是这样。经过一些试验和错误,我发现了它。(注意:看起来您使用的是旧版 Python,因此语法可能需要对此解决方案进行一些调整。)

import json


class Child(dict):
    def __init__(self, **kwargs):
        super(Child, self).__init__(**kwargs)


class Parent(dict):
    def __init__(self, **kwargs):
        super(Parent, self).__init__(**kwargs)


parent = Parent(child=Child())

print(type(parent['child']))

if __name__ == '__main__':
    dumped = json.dumps(parent)
    loaded = json.loads(dumped)
    parent_2 = Parent(child=Child(**loaded)) # Changed how you call Parent
    print(type(parent_2['child']))

Parent如果不使用dict初始化 as调用 args,除非您添加额外的逻辑来检测类型,否则我们不会期望检测到类型ChildChild


推荐阅读