python json 自定義對(duì)象 全自動(dòng) 序列化和反序列化

python內(nèi)置的json序列化不能自動(dòng)將對(duì)象序列化,必須寫encoder才能將其序列化,反序列化也是。所以我寫了一個(gè)通用的序列化方案,在序列化時(shí)將類的信息也保存進(jìn)去,反序列化時(shí)則自動(dòng)將通過類的初始化創(chuàng)建對(duì)象。
注意反序列化時(shí),對(duì)象的構(gòu)造函數(shù)必須包含全部的序列化屬性

序列化

serializable = (list, str, dict, int, bool, float, set, tuple)

def obj2dict(obj):
    if type(obj) in serializable:
        if type(obj) in (list, set, tuple):
            return [obj2dict(o) for o in obj]
        elif isinstance(obj, (dict,)):
            return {k: obj2dict(v) for k, v in obj.items()}
        else:
            return obj
    else:
        if isinstance(obj, (list, set, tuple)):
            return dict(
                type=type(obj).__name__,
                values=[obj2dict(x) for x in obj]
            )
        dic: dict[str, Any] = dict()
        if hasattr(obj, "skip_attr"):
            skip = getattr(obj, "skip_attr")
        else:
            skip = ()
        for attr in obj.__dict__:
            if attr not in skip:
                dic[attr] = obj2dict(getattr(obj, attr))
        return dict(
            type=type(obj).__name__,
            values=dic
        )

反序列化

def dict2obj(obj):
    if isinstance(obj, dict):
        if "type" in obj and "values" in obj:
            for module in modules.values():
                if hasattr(module, obj["type"]):
                    ty = getattr(module, obj["type"])
                    if isinstance(obj["values"], dict):
                        obj["values"] = dict2obj(obj["values"])
                        return ty(**obj["values"])
                    elif isinstance(obj["values"], (list, set)):
                        return ty(*[dict2obj(x) for x in obj["values"]])
        else:
            for k, v in obj.items():
                obj[k] = dict2obj(v)
                return obj
            return obj
    elif isinstance(obj, (list, set, tuple)):
        for o in obj:
            o = dict2obj(o)
        return obj
    else:
        return obj

使用方式

a = student("a", 1)
a_str = json.dumps(obj2dict(a))
b_dict = json.loads(a_str)
b = dict2obj(b_dict)
print(b.name)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容