当前位置: 动力学知识库 > 问答 > 编程问答 >

Parameterizing Python's json.loads() object_hook to a Factory Method

问题描述:

I am currently writing an application that utilizes python's JSON module, and thought that it would be nice to resurrect JSON data into an appropriate python object.

The below works perfectly.

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']

...

After five or more attributes, this gets a little annoying having to rewriting functions for each attribute. Considering this is a perfect spot for a factory method, the only things needed are parameters.

How can I simulate this?

I ran through the json documentation for python multiple times, and am frustrated why this functionality isn't [immediately] trivial.

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._getAttribute, args=["attrA"])

self.attrB = json.loads(JSON_Object, object_hook=self._getAttribute, args=["arrtB"])

...

# super simple, general, parameterized callback function for json.loads()

def _getAttribute(self, JSON_Object, args) :

if args[0] in JSON_Object :

return JSON_Object[args[0]]

A non-trivial solution is fine but the bigger question is why is this not immediately possible??

网友答案:

You've picked a really weird way to use object_hook. object_hook is designed for customizing the deserialization process to convert dicts to some other data type, not for reading fields out of the JSON. If you just want to read fields, you should loads the JSON without an object_hook and then read fields out of the resulting dict with ordinary indexing syntax:

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

or if you want to dump all fields into identically-named attributes of the object:

self.__dict__.update(json.loads(JSON_Object))

If you want to apply that recursively, that would be a good time to use object_hook:

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)
分享给朋友:
您可能感兴趣的文章:
随机阅读: