I have two classes A and B, each one storing references to objects of the other class in lists:
class A:
def __init__(self,name):
self.name = name
self.my_Bs = []
def registerB(self,b):
self.my_Bs.append(b)
class B:
def __init__(self,name):
self.name = name
self.my_As = []
def registerA(self,a):
self.my_As.append(a)
Now, my app builds two lists, one of objects of A, one of objects of B, having cross references.
# a list of As, a list of Bs
list_of_As = [A('firstA'), A('secondA')]
list_of_Bs = [B('firstB'), B('secondB')]
# example of one cross-reference
list_of_As[0].registerB(list_of_Bs[1])
list_of_Bs[1].registerA(list_of_As[0])
Obviously, if I call json.dumps()
on either list_of_...
, I get a circular reference error.
What I want to do to circumvent that issue is to dump JSON with list of elements name
attributes instead of lists of objects themselves:
# This is what I want to obtain for
# the JSON for list_of_As
[
{'name' : 'firstA', 'my_Bs': ['secondB']},
{'name' : 'secondA', 'my_Bs': []}
]
The only way I can think of is to maintain in each class an additional list of strings (respectively my_Bs_names
and my_As_names
) and to use JSONEncoder
as follows:
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, 'A'):
return { # filter out the list of B objects
k: v for k, v in obj.__dict__.items() if k != 'my_Bs'
}
if isinstance(obj, 'B'):
return { # filter out the list of A objects
k: v for k, v in obj.__dict__.items() if k != 'my_As'
}
return super(MyEncoder, self).default(obj)
# Use the custom encoder to dump JSON for list_of_As
print json.dumps(list_of_As, cls=MyEncoder)
If I am not mistaken, I would get the following result:
# This is what I obtain for
# the JSON for list_of_As with the code above
[
{'name' : 'firstA', 'my_Bs_names': ['secondB']},
{'name' : 'secondA', 'my_Bs_names': []}
]
Is there a more elegant way of getting this result? For instance one that does not require any additional lists of strings?