-3

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".

6
  • I think you're asking "how can I serialize to JSON an instance of class A?" Commented Oct 25, 2021 at 12:21
  • @jarmod I want to serialize recursively all the objects. Commented Oct 25, 2021 at 12:23
  • What code do you have that results in circular reference? Where is the circular reference? Commented Oct 25, 2021 at 12:27
  • @jarmod This is dummy code, in real code if i use xyz = json.dumps(<OBJ>) I am getting circular reference error. so what might be the reason? Commented Oct 25, 2021 at 12:30
  • 1
    If you're unable to share the real code, you should at least modify your post to include an equivalent circular reference otherwise we are all just guessing. Commented Oct 25, 2021 at 12:34

1 Answer 1

4

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}'
Sign up to request clarification or add additional context in comments.

2 Comments

What if I don't want to change the classes into dataclass as it is real project? Is there any way?
@SurendranathaReddyT Why don't you want to use dataclasses? If you are using Python 3, dataclasses will make your code quality better. Dataclasses are essentially the same as classes under the hood.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.