【问题标题】:How to access Object of Objects as JSON in Python?如何在 Python 中将对象的对象作为 JSON 访问?
【发布时间】:2021-12-10 22:20:30
【问题描述】:

我有 3 节课。

    Class A:
      def __init__(self,a1,a2,a3)
        self.a1 = 10
        self.a2 = B()
        self.a3 =20
    
    Class B:
      def __init__(self,b1,b2,b3)
        self.b1 = C()
        self.b2 = 30
        self.b3 = 40
    
    Class C:
      def __init__(self,c1,c2,c3):
        self.c1 = 50
        self.c2 = 60
        self.c3 = 70

输入 = [xxx 处的对象 A]

我想获取对象中的所有细节作为输出。

输出应该是 [{a1:10,a2:{b1: {c1:50, c2:60, c3: 70}, b2:30, b3:40}, a3: 20}]强>

我试过这种方式,但工作很忙。

for each in input[0].__dict__:
  for x in each.__dict__:

有什么解决办法吗?偏离路线 - 没有“ValueError:检测到循环引用”。

【问题讨论】:

  • 我想您是在问“如何将 A 类的实例序列化为 JSON?”
  • @jarmod 我想递归地序列化所有对象。
  • 你有什么代码导致循环引用?循环引用在哪里?
  • @jarmod 这是虚拟代码,如果我使用 xyz = json.dumps() 在实际代码中出现循环引用错误。那么可能是什么原因呢?
  • 如果您无法分享真实代码,您至少应该修改您的帖子以包含等效的循环引用,否则我们都只是猜测。

标签: python json oop


【解决方案1】:

您可能有兴趣在这种情况下使用dataclass

from dataclasses import dataclass

@dataclass
class C:
    c1: int
    c2: int
    c3: int

@dataclass
class B:
    b1: C
    b2: int
    b3: int

@dataclass
class A:
    a1: int
    a2: B
    a3: int

那么例如

>>> c = C(50, 60, 70)
>>> b = B(c, 30, 40)
>>> a = A(10, b, 20)
>>> a
A(a1=10, a2=B(b1=C(c1=50, c2=60, c3=70), b2=30, b3=40), a3=20)

鉴于此对象层次结构,您可以使用 like this 方法将其转换为字典

>>> import dataclasses
>>> dataclasses.asdict(a)
{'a1': 10, 'a2': {'b1': {'c1': 50, 'c2': 60, 'c3': 70}, 'b2': 30, 'b3': 40}, 'a3': 20}

最后得到一个有效的json字符串

>>> import json
>>> json.dumps(dataclasses.asdict(a))
'{"a1": 10, "a2": {"b1": {"c1": 50, "c2": 60, "c3": 70}, "b2": 30, "b3": 40}, "a3": 20}'

【讨论】:

  • 如果我不想将类更改为数据类,因为它是真正的项目怎么办?有什么办法吗?
  • @SurendranathaReddyT 为什么你不想使用数据类?如果您使用的是 Python 3,数据类将使您的代码质量更好。数据类本质上与底层的类相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 2015-04-20
  • 2022-07-06
  • 2012-06-29
  • 2013-02-09
  • 2012-06-06
相关资源
最近更新 更多