参数化Python的json.loads()对象挂钩到工厂方法

2024-09-29 23:29:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在编写一个利用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}$

一个非琐碎的解决方案是好的,但更大的问题是为什么这不是立即可能的??在


Tags: 方法selfnonejsonifobjectinitdef
1条回答
网友
1楼 · 发布于 2024-09-29 23:29:42

您选择了一种非常奇怪的方法来使用object_hookobject_hook用于定制反序列化过程,将dict转换为其他数据类型,而不是从JSON中读取字段。如果您只想读取字段,您应该loads不带object_hook的JSON,然后使用普通索引语法从生成的dict中读取字段:

data = json.loads(JSON_Object)
self.attrA = data['attrA']
self.attrB = data['attrB']
...

或者,如果要将所有字段转储到对象的同名属性中:

^{pr2}$

如果您想递归地应用它,那个将是使用^{的好时机:

class JSON_Namespace(object):
    def __init__(self, data_dict):
        self.__dict__.update(data_dict)
    @classmethod
    def load_from_json(cls, json_string):
        return json.loads(json_string, object_hook=cls)

相关问题 更多 >

    热门问题