使任何类型的json可序列化
alljson的Python项目详细描述
使任何类型的json可序列化。
一个python模块,它使json.dumps与几个内置的 和stdlib类型。用于注册任何自定义类型的钩子 提供。
安装
只需使用pip安装alljson或将其添加到项目依赖项:
pip install alljson
支持的类型
安装后,以下类型是json可序列化的:
- 发电机
- set和frozenset
- dictitem/key/value迭代器和视图
- datetime.date和datetime.datetime(作为iso格式的字符串)
- uuid.UUID
- decimal.Decimal(序列化为字符串以保持精度)
- reversed结果
除此之外,还支持以下python 3类型:
- map,filter,range迭代器
- enum.Enum
- pathlib.Path
- types.MappingProxyType
- 实现Sequence和Mappingabc接口的类
注册自定义类型
要注册新类型,请使用alljson.register_encoder(type, encoder_function)。encoder_function应该接受给定的对象 键入作为唯一参数并返回一个简单的json可序列化 python值(例如dict或str)。
例如:
import arrow import alljson alljson.register_encoder(arrow.Arrow, arrow.Arrow.isoformat)
致谢
- pth技巧是从令人愉快的future-fstrings项目中偷来的