zstd算法压缩解压缩json - python3示例

import zstandard as zstd
import base64

def zstd_compress_b64(data):
    """使用zstd算法对data:str压缩并base64编码"""
    binary_data = data.encode('utf-8')
    compressor = zstd.ZstdCompressor()
    compressed_data = compressor.compress(binary_data)
    base64_data = base64.b64encode(compressed_data)
    return base64_data.decode('utf-8')


def zstd_decompress_b64(data):
    """使用zstd算法对data进行base64解压缩并然后解zstd压缩"""
    compressed_data = base64.b64decode(data)
    decompressor = zstd.ZstdDecompressor()
    decompressed_data = decompressor.decompress(compressed_data)
    return decompressed_data.decode('utf-8')


def tst():
    org_file = "test.json"
    com_file = "test_compressed.json"
    dcom_file = "test_decompressed.json"
    
    with open(org_file, 'r') as f:
        org_json_str = f.read()
    
    com_data = zstd_compress_b64(org_json_str)
    with open(com_file, 'w') as f:
        f.write(com_data)
    
    dcom_data = zstd_decompress_b64(com_data)
    with open(dcom_file, 'w') as f:
        f.write(dcom_data)
    
    # # 数据中有\r\n不影响
    # with open("output.json","r") as f:
    #     tst_data_str = f.read()
    
    # tst_dcomm_str = gzip_decompress_base64(tst_data_str)
    # with open("output_handle.json","w") as f:
    #     f.write(tst_dcomm_str)


if __name__ == "__main__":
    tst()
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值