如何在Python中访问对象的JSON对象?



我有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

input = [object A at xxx]

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

输出应该[{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:循环引用检测"

您可能对在本例中使用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)

给定此对象层次结构,您可以使用如下方法将其转换为字典

>>> 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}'