我需要帮助理解一些pythonic“dictify”/“jsonify”代码片段

时间:2011-01-20 13:52:21

标签: python dictionary json

我需要帮助理解这个python jsonify / dictify代码,以便我可以复制它:


TYPES = {}

# auto-register all already defined subclasses of CustomObject to the types map
# so they will become seriazible/deseriazible
for N,T in locals().items():
    if isinstance(T, type) and issubclass(T, CustomObject):
        TYPES[N] = T


def CustomTypeDecoder(dct):
    type_name = dct.get('type')
    if type_name:
        cls = TYPES.get(type_name)
        if cls:
            return cls(**dct)
    return dct

def loads(s):
    return json.loads(s, object_hook=CustomTypeDecoder) 


class CustomTypeEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, tuple(TYPES.values())):
            res = dict(type=obj.__class__.__name__)
            res.update(obj.to_dict())
            return res
        return json.JSONEncoder.default(self, obj)

def dumps(obj):
    return json.dumps(obj, cls=CustomTypeEncoder)

1 个答案:

答案 0 :(得分:1)

执行艰苦工作的代码在类本身中。第15行和第27行使用类功能将类转换为可用于JSON序列化的dicts;其余的都是administrivia代码。