Canonical JSON
项目描述
功能
将对象和数组编码为RFC 7159 JSON。
排序对象键,以便每次都得到相同的结果。
不包含无关紧要的空白字符,以使输出尽可能小。
仅转义必须转义的字符,U+0000到U+0019 / U+0022 / U+0056,以使输出尽可能小。
为每个转义字符使用最短的转义序列。
将JSON编码为UTF-8。
可以配置为编码stdlib JSON编码器未知的自定义类型。
支持Python 3.7及更高版本。
安装
pip install canonicaljson
使用
将对象编码为canonicaljson
import canonicaljson
assert canonicaljson.encode_canonical_json({}) == b'{}'
还有迭代版本
import canonicaljson
assert b''.join(canonicaljson.iterencode_canonical_json({})) == b'{}'
可以使用以下方式选择底层的JSON实现
import json
import canonicaljson
canonicaljson.set_json_library(json)
预序列化钩子允许您编码标准库JSONEncoder无法编码的对象。
import canonicaljson
from typing import Dict
class CustomType:
pass
def callback(c: CustomType) -> Dict[str, str]:
return {"Hello": "world!"}
canonicaljson.register_preserialisation_callback(CustomType, callback)
assert canonicaljson.encode_canonical_json(CustomType()) == b'{"Hello":"world!"}'