将一些常见文件格式编码/解码为 json 的 Python 包
项目描述
锌JSON
打包将一些常见的文件格式编码/解码为 json
可通过pip install znjson
与pickle
此相比,它允许将可读的 json 文件与一些序列化数据结合起来。
例子
import numpy as np
import json
import znjson
data = json.dumps(
obj={"data_np": np.arange(2), "data": [x for x in range(10)]},
cls=znjson.ZnEncoder,
indent=4
)
_ = json.loads(data, cls=znjson.ZnDecoder)
生成的*.json
文件是部分可读的,如下所示:
{
"data_np": {
"_type": "np.ndarray_small",
"value": [
0,
1
]
},
"data": [
0,
1,
2,
3,
4
]
}
自定义转换器
ZnJSON 允许您轻松添加自定义转换器。让我们为datetime.datetime
.
from znjson import ConverterBase
from datetime import datetime
class DatetimeConverter(ConverterBase):
"""Encode/Decode datetime objects
Attributes
----------
level: int
Priority of this converter over others.
A higher level will be used first, if there
are multiple converters available
representation: str
An unique identifier for this converter.
instance:
Used to select the correct converter.
This should fulfill isinstance(other, self.instance)
or __eq__ should be overwritten.
"""
level = 100
representation = "datetime"
instance = datetime
def _encode(self, obj: datetime) -> str:
"""Convert the datetime object to str / isoformat"""
return obj.isoformat()
def _decode(self, value: str) -> datetime:
"""Create datetime object from str / isoformat"""
return datetime.fromisoformat(value)
这允许我们使用这个新的序列化程序:
znjson.register(DatetimeConverter) # we need to register the new converter first
json_string = json.dumps(dt, cls=znjson.ZnEncoder, indent=4)
json.loads(json_string, cls=znjson.ZnDecoder)
并会导致
{
"_type": "datetime",
"value": "2022-03-11T09:47:35.280331"
}
项目详情
下载文件
下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。
源分布
znjson-0.1.3.tar.gz
(12.0 kB
查看哈希)
内置分布
znjson-0.1.3-py3-none-any.whl
(15.5 kB
查看哈希)