如何将嵌套类转换为 json 或 dict?
我有如下的类:
class Base:
def __init__(self):
self.var1 = “variable”
class Child:
def __init__(self):
self.base = Base()
self.var2 = False
class RootChild:
def __init__(self):
self.child = Child()
self.var3 = “variable”
self.base = Base()
我想保存“RootChild”的一个实例,其所有字段都以 json 表示。关于此任务有很多主题,但我无法理解它们的差异和用例。这个问题的大多数 Pythonic 解决方案是什么?
I have class of classes as below:
class Base:
def __init__(self):
self.var1 = “variable”
class Child:
def __init__(self):
self.base = Base()
self.var2 = False
class RootChild:
def __init__(self):
self.child = Child()
self.var3 = “variable”
self.base = Base()
I want to save an instance of ‘RootChild’ with all fields of it represented in json. There are a lot of topics about this task, but I could not understand their differences and use cases. What are most pythonic solutions to this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的里程会有所不同 - 从使用“序列化器”策略:一层机制知道如何从您的类映射到 Json 并返回,
这可能需要大量工作(手动描述应该序列化/反序列化的每个字段) - https://docs.pylonsproject.org/projects/colander/en/latest/
或者您可以构建一个自定义 JSON 编码器,该编码器仅检查它是否是已知类,然后返回一个包含所有字段的字典(可以通过内省自动提取)-(检查示例以扩展编码器:https://docs.python.org/3/library/json.html )
无论如何,都有很多权衡和不同级别的工作 -
如果您打算在具有相同类的 Python 应用程序中读回 JSON,您可以使用“jsonpickle” - 它将向您的 JSON 添加额外的元数据,但将确保所有对象的往返完全按原样:< a href="https://jsonpickle.github.io/" rel="nofollow noreferrer">https://jsonpickle.github.io/
不使用任何其他库,并假设您只需要导出类,自定义编码器策略可以有点简单:
在交互环境上:
Your mileage will vary - from using a "serializer" strategy: a layer of mechanisms that will know how to map from your classes to Json and back,
which can be a lot of work (to the point of hand-describing each field that should be serialized/unserialized) - https://docs.pylonsproject.org/projects/colander/en/latest/
Or you could build a custom JSON encoder that will just check if it is a known class and then return a dict with all its fields (which can be extracted automatically by introspection) - (check the example to extend the encoder here: https://docs.python.org/3/library/json.html )
Any way there are lots of trade-offs and differing level of work -
if you plan to read the JSON back in Python apps which have the same classes, you could use "jsonpickle" - it will add extra meta-data to your JSON, but will ensure round tripping of all your objects exactly as they are: https://jsonpickle.github.io/
Without using any other lib, and assuming you just need to export your classes, the custom encoder strategy can be somewhat simple:
And on the interactive environment: