【发布时间】: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