python - python - 在嵌套对象中,如何返回对象dicts的json输出?

假设我得到了这些类,需要它们的属性和属性字典作为json输出:


from random import randint



class A:


 def __init__(self, a, b):


 self.a = a


 self.b = b


 def out_dict(self):


 return self.__dict__



class B:


 def __init__(self, B_a, list_of_A):


 self.b_arg = B_a


 self.list_of_A = list_of_A


 def out_dict(self):


 return self.__dict__



class C:


 def __init__(self, C_a, list_of_B):


 self.c_arg = C_a


 self.list_of_B = list_of_B


 def out_dict(self):


 return self.__dict__



list_of_A = [A(randint(0,100), randint(0,100)) for _ in range(5)]


list_of_B = [B(5, list_of_A) for _ in range(3)]


c = C(10, list_of_B)


print(c.out_dict())



以上代码的输出为:


{'c_arg': 10,


'list_of_B': [<__main__.B at 0x207613625c0>,


 <__main__.B at 0x2076110bdd8>,



正如你所看到的,对象是嵌套的,输出中并没有提到类的所有属性,另一方面,需要一些输出,如下所示:


{"C":


 {"list_of_B":[


"B0": {


 {"list_of_A":


 {["0":{"a":10,"b":21},"2":{"a":1,"b":3}, 


"1":{"a":10,"b":21},"2":{"a":54,"b":12},


"2":{"a":10,"b":21},"2":{"a":12,"b":32},


 ]}


"b_arg": 27


 }



 },


"B1": {


 {"list_of_A":


 {["0":{"a":10,"b":21},"2":{"a":1,"b":3}, 


"1":{"a":10,"b":21},"2":{"a":54,"b":12},


"2":{"a":10,"b":21},"2":{"a":12,"b":32},


 ]}


"b_arg": 27


 }



 },


 ]


"c_arg": 95


 }


}



需要将它们输出为json。

时间:

你的核心逻辑是正确的,
然而,问题是你的list_of_A,list_of_B和c变量指向你的类
简单的操作


from random import randint


class A:


 def __init__(self, a, b):


 self.a = a


 self.b = b



 def out_dict(self):


 return self.__dict__



class B:


 def __init__(self, B_a, list_of_A):


 self.b_arg = B_a


 self.list_of_A = list_of_A


 def out_dict(self):


 return self.__dict__



class C:


 def __init__(self, C_a, list_of_B):


 self.c_arg = C_a


 self.list_of_B = list_of_B


 def out_dict(self):


 return self.__dict__



list_of_A = [A(randint(0,100), randint(0,100)).out_dict() for _ in range(5)]


#This ^


list_of_B = [B(5, list_of_A).out_dict() for _ in range(3)]


#Solves ^


c = C(10, list_of_B).out_dict()


#It ^


print(c)



修复问题

...