python - 如何用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.loads
Parent['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 字典?
解决方案
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,除非您添加额外的逻辑来检测类型,否则我们不会期望检测到类型Child
。Child
推荐阅读
- python - Google Analytics v4 中的正则表达式以获取不包含“?”的 pagePath
- c# - 如何调整 ListView 控件内的图像大小?
- reactjs - 每次用户导航到新页面时调用/运行动画
- python - Python 聊天客户端和服务器套接字问题
- sql - 添加在 case 语句中使用的列别名值
- python - Azure 云功能无法访问依赖项
- python - 如何使用 Python 检查某人在 Instagram 上有多少关注者?
- c# - 领英API。如何找回自己的帖子
- python - 从第二个字典更新字典键和值
- angular - 在 Angular 7 拦截器中调用异步函数