我目前正在编写一个利用python的JSON模块的应用程序,并认为将JSON数据恢复到适当的python对象中会很好。在
下面的方法非常有效。在
Class MyClass :
def __init__(self, argA = None, argB = None, ... , JSON_Object=None):
self.attrA = argA
self.attrB = argB
...
if JSON_Object :
self.attrA = json.loads(JSON_Object, object_hook=self._getAttributeA)
self.attrB = json.loads(JSON_Object, object_hook=self._getAttributeB)
...
# Individual call back functions for the init... *yucky*.
def _getAttributeA(self, JSON_Object) :
if 'attrA' in JSON_Object :
return JSON_Object['attrA']
def _getAttributeB(self, JSON_Object) :
if 'attrB' in JSON_Object :
return JSON_Object['attrB']
...
在五个或更多的属性之后,不得不为每个属性重写函数会有点烦人。考虑到这是工厂方法的最佳位置,只需要参数。在
我多次浏览了json documentation for python,对为什么这个功能不是[立即]微不足道感到沮丧。在
^{pr2}$一个非琐碎的解决方案是好的,但更大的问题是为什么这不是立即可能的??在
您选择了一种非常奇怪的方法来使用
object_hook
。object_hook
用于定制反序列化过程,将dict转换为其他数据类型,而不是从JSON中读取字段。如果您只想读取字段,您应该loads
不带object_hook
的JSON,然后使用普通索引语法从生成的dict中读取字段:或者,如果要将所有字段转储到对象的同名属性中:
^{pr2}$如果您想递归地应用它,那个将是使用^{的好时机:
相关问题 更多 >
编程相关推荐