前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 序列化/反序列化自定义类型

Python 序列化/反序列化自定义类型

作者头像
雪飞鸿
发布2020-09-21 18:04:25
8510
发布2020-09-21 18:04:25
举报
文章被收录于专栏:me的随笔

内置json模块对于Python内置类型序列化的描述

代码语言:javascript
复制
    """Extensible JSON <http://json.org> encoder for Python data structures.

    Supports the following objects and types by default:

    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict              | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str               | string        |
    +-------------------+---------------+
    | int, float        | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+

    To extend this to recognize other objects, subclass and implement a
    ``.default()`` method with another method that returns a serializable
    object for ``o`` if possible, otherwise it should call the superclass
    implementation (to raise ``TypeError``).

    """

内置json模块对于Python内置类型反序列化的描述

代码语言:javascript
复制
    """Simple JSON <http://json.org> decoder

    Performs the following translations in decoding by default:

    +---------------+-------------------+
    | JSON          | Python            |
    +===============+===================+
    | object        | dict              |
    +---------------+-------------------+
    | array         | list              |
    +---------------+-------------------+
    | string        | str               |
    +---------------+-------------------+
    | number (int)  | int               |
    +---------------+-------------------+
    | number (real) | float             |
    +---------------+-------------------+
    | true          | True              |
    +---------------+-------------------+
    | false         | False             |
    +---------------+-------------------+
    | null          | None              |
    +---------------+-------------------+

    It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
    their corresponding ``float`` values, which is outside the JSON spec.

    """

 分别使用pickle和json模块来实现自定义类型的序列化和反序列化

代码语言:javascript
复制
class Person():
    """人类"""
    # __slots__ = ['age']
    # __dict__ = ['age', 'name']
    _age: int = 0

    def __init__(self, age, name='eason'):
        # json.JSONEncoder.__init__(self, skipkeys=True)
        self.age = age
        self.name = name
        # self.name = name

    # def __dir__(self):
    #     return ['age', 'name']

    @property
    def age(self) -> int:
        return self._age

    @age.setter
    def age(self, age: int):
        print('set age')
        if age <= 0:
            raise ValueError('age')
        self._age = age

    def hello(self):
        print('==============hello-locals===============')
        print(locals())
代码语言:javascript
复制
import pickle
import json


from demo.src.models.person import Person
# import demo.src.models.person.Person


class PersonJSONEncoder(json.JSONEncoder):
    def default(self, o: Person):
        # 返回字典类型
        return {"name": o.name, "age": o.age}

    # def encode(self, o: Person):
    #     # 直接返回字典,
    #     return str({"age": o.age, "name": o.name})


class PersonJSONDecoder(json.JSONDecoder):
    def decode(self, s: str):
        obj_dict = json.loads(s)
        # return Person(obj_dict['age'], obj_dict['age'])
        return Person(**obj_dict)







p = Person(28, 'wjchi')

# bytes
# p_bytes = pickle.dumps(p)
# print(type(p_bytes), p_bytes)
# p_obj = pickle.loads(p_bytes)
# print(type(p_obj), p_obj.age)

# string

# p_str = json.dumps(p, default=lambda obj: obj.__dict__)
# print(type(p_str), p_str)
# p_dict = json.loads(p_str)
# print(type(p_dict), p_dict['age'])

p_str = json.dumps(p, cls=PersonJSONEncoder)
print(type(p_str), p_str)
p_dict = json.loads(p_str)
# print(type(p_dict), p_dict['age'])
# p_obj = json.loads(p_str, cls=PersonJSONDecoder)
p_obj = Person(**p_dict)
print(type(p_obj), p_obj.age)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档