【问题标题】:I need help understanding some pythonic "dictify" / "jsonify" code fragments我需要帮助理解一些pythonic“dictify”/“jsonify”代码片段
【发布时间】:2011-01-20 13:52:20
【问题描述】:

我需要帮助理解这个 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)

【问题讨论】:

  • 你到底有什么不明白的?具体一点。
  • 一切......我知道它正在注册一种 JSON,但就是这样。
  • "Everything" 并不具体。请分享你的目标是什么。你想修改它吗?延长它?调试吗?用它?你有什么问题?你没有做什么?
  • 除了代码的高级用途之外,我什么都不明白。它在我的代码库中,我需要用它来扩展 JSON 类的编码/解码。
  • @user407601:请更新您的问题以具体描述“扩展 JSON 类的编码/解码”的含义。详细。

标签: python dictionary json


【解决方案1】:

完成繁重工作的代码在类本身中。第 15 行和第 27 行使用类功能将类从字典转换为 JSON 序列化;剩下的都是管理密码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多