如何将嵌套类转换为 json 或 dict?

发布于 2025-01-10 09:12:29 字数 432 浏览 0 评论 0原文

我有如下的类:


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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自演自醉 2025-01-17 09:12:29

您的里程会有所不同 - 从使用“序列化器”策略:一层机制知道如何从您的类映射到 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/

不使用任何其他库,并假设您只需要导出类,自定义编码器策略可以有点简单:

import json
class SimpleObject(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, "__dict__"):
            return {key:value for key, value in obj.__dict__.items() if not key.startswith("_")}
        return super().default(obj)
a = RootChild()

在交互环境上:

In [52]: a = RootChild()
In [53]: print(json.dumps(a, cls=SimpleObject, indent=4))
{
    "child": {
        "base": {
            "var1": "variable"
        },
        "var2": false
    },
    "var3": "variable",
    "base": {
        "var1": "variable"
    }
}

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:

import json
class SimpleObject(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, "__dict__"):
            return {key:value for key, value in obj.__dict__.items() if not key.startswith("_")}
        return super().default(obj)
a = RootChild()

And on the interactive environment:

In [52]: a = RootChild()
In [53]: print(json.dumps(a, cls=SimpleObject, indent=4))
{
    "child": {
        "base": {
            "var1": "variable"
        },
        "var2": false
    },
    "var3": "variable",
    "base": {
        "var1": "variable"
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文