【发布时间】:2019-07-19 06:16:49
【问题描述】:
我有两个类 A 和 B,每个类都在列表中存储对另一个类的对象的引用:
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)
现在,我的应用构建了两个列表,一个是 A 的对象,一个是 B 的对象,具有交叉引用。
# 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])
显然,如果我在 list_of_... 上调用 json.dumps(),我会收到循环引用错误。
为了规避这个问题,我想要做的是使用 元素列表 name 属性 转储 JSON,而不是 对象本身的列表:
# This is what I want to obtain for
# the JSON for list_of_As
[
{'name' : 'firstA', 'my_Bs': ['secondB']},
{'name' : 'secondA', 'my_Bs': []}
]
我能想到的唯一方法是在每个类中维护一个额外的字符串列表(分别为my_Bs_names 和my_As_names)并使用JSONEncoder,如下所示:
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)
如果我没记错的话,我会得到以下结果:
# 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': []}
]
有没有更优雅的方法来获得这个结果?例如,不需要任何额外的字符串列表?
【问题讨论】:
标签: python json serialization