0

I want to create a json that describes ,in a completely generic form ,a nested object. For example:

class A():
    def __init__(self,x):
        self.x = x

class B():
    def __init__(self,a: 'A'):
        self.a = a

class C():
    def __init__(self,a: 'A'):
        self.a = a

I want to create class A then transfer it to B and C and describe it all on json ans generate this structure automatically. A schematic example of the json file that I would like to write:

{
    "A":{"x": 3},
    "B":{"a": "A"},
    "C":{"a": "A"},
}

The code should look like that:

tree = json.load(json_file)
print(tree.B.a)
print(tree.C.a)

How can I implement this in python?

HadaSh
  • 1
  • 1
  • You need to implement a method that describes own class and calls inner objects to describe themselves. Basic recursion. – go2nirvana Mar 15 '21 at 13:49
  • Yes but I want to use something like `tree = json.load(json_file)` and get a tree of all this objects in a way I can call tree.B.a. – HadaSh Mar 15 '21 at 13:55
  • 1
    Then you will have to also write a custom serialiser for your classes. https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable – go2nirvana Mar 15 '21 at 13:57
  • But how you can create A then transfer it to B and C without writing it in code explicitly? – HadaSh Mar 15 '21 at 14:03
  • Simple: you can't – go2nirvana Mar 15 '21 at 15:09

0 Answers0