zoukankan      html  css  js  c++  java
  • Python json序列化时default/object_hook指定函数处理

    在Python中,json.dumps函数接受参数default用于指定一个函数,该函数能够把自定义类型的对象转换成可序列化的基本类型。json.loads函数接受参数objec_thook用于指定函数,该函数负责把反序列化后的基本类型对象转换成自定义类型的对象。

    boy1 = boy('Will', 20)
    
    #default method for decode
    def boydefault(obj):
        if isinstance(obj, boy):
            return {'name': obj.name, 'age': obj.age}
        return obj;
    
    def boyhook(dic):
        print('test')
        if dic['name']:
            return boy(dic['name'], dic['age'])
        return dic
    
    boy_encode_str = json.dumps(boy1, default=boydefault)
    new_boy = json.loads(boy_encode_str, object_hook=boyhook)
    print(boy_encode_str)
    print(new_boy)
    
  • 相关阅读:
    第九次任务
    第八次任务
    第七次任务
    第六次任务
    第四天半任务
    第四天任务
    第三天任务
    第二天任务
    第一天任务
    第⑩天任务
  • 原文地址:https://www.cnblogs.com/ccorz/p/Python-json-xu-lie-hua-shidefaultobjecthook-zhi-di.html
Copyright © 2011-2022 走看看