我正在尝试使用以下程序模拟问题陈述:
import json
class System:
def __init__(self):
self.model = "abc"
self.fwVersion = "123"
self.prevfwVersion = "456"
self.safemodeVersion = "5756"
def __setitem__(self, key, val):
self.__dict__[key] = val
def __getitem__(self, key):
return self.__dict__[key]
def toJSON(self):
return self.__dict__
class Mainwall:
def __init__(self):
self.system = System()
def __setitem__(self, key, val):
self.__dict__[key] = val
def __getitem__(self, key):
return self.__dict__[key]
def toJSON(self):
return self.__dict__
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'toJSON'):
return obj.toJSON()
else:
return json.JSONEncoder.default(self, obj)
fw = Mainwall()
def my_print():
print(json.dumps(fw.toJSON(), cls=ComplexEncoder, indent=4))
if __name__ == '__main__':
my_print()
由于python词典不保留插入顺序,因此上述程序的输出始终具有不同的键顺序。
说,第一次打印:
{
"system": {
"safemodeVersion": "5756",
"prevfwVersion": "456",
"fwVersion": "123",
"model": "abc"
}
}
第二次打印:
{
"system": {
"fwVersion": "123",
"prevfwVersion": "456",
"safemodeVersion": "5756",
"model": "abc"
}
}
但是,在输出中我想保留类成员初始化的顺序。即,完全如下:
{
"system": {
"model": "abc",
"fwVersion": "123",
"prevfwVersion": "456",
"safemodeVersion": "5756",
}
}
如何使用OrderedDict()或其他方法实现同一示例的预期输出?
答案 0 :(得分:1)
我为你做了一个解决方案。我邀请您查看System()
课程。我创建了OrderedDict()
而不是四个self
属性。然后,在方法toJSON(self):
中,我将返回之前设置的self.__dict__
,而不是返回OrderedDict()
属性。
class System:
def __init__(self, model='abc', fwVersion='123', prevfwVersion='456', safemodeVersion='5756'):
self.my_ordered_dict = OrderedDict()
self.my_ordered_dict['model'] = model
self.my_ordered_dict['fwVersion'] = fwVersion
self.my_ordered_dict['prevfwVersion'] = prevfwVersion
self.my_ordered_dict['safemodeVersion'] = safemodeVersion
# self.model = "abc"
# self.fwVersion = "123"
# self.prevfwVersion = "456"
# self.safemodeVersion = "5756"
def __setitem__(self, key, val):
self.__dict__[key] = val
def __getitem__(self, key):
return self.__dict__[key]
def toJSON(self):
return self.my_ordered_dict
此System()
类而不是上面的类,具有相同的代码,输出...
{
"system": {
"model": "abc",
"fwVersion": "123",
"prevfwVersion": "456",
"safemodeVersion": "5756"
}
}
答案 1 :(得分:0)
升级到python 3.6解决了这个问题。