简体   繁体   中英

How to access Object of Objects as JSON in Python?

I have 3 classes.

    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]

I want to get all details in objects as output.

output should be [{a1:10,a2:{b1: {c1:50, c2:60, c3: 70}, b2:30, b3:40}, a3: 20}]

I tried this way, but it is hectic job.

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

Any solution? Off course- Without "ValueError: Circular reference detected".

You might be interested in using a dataclass in this case

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

Then for example

>>> 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)

Given this object hierarchy you can convert to a dictionary using a method like this

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

And finally to get a valid json string

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM