python - Gzip 到 base64 编码将字符添加到 JSON 字符串

标签 python json python-3.x base64 gzip

我有一个嵌套的 python 字典,它被序列化为 json 字符串,我将其进一步转换为压缩的 Gzip 文件并对其进行 base64 编码。但是,一旦我将其转换回 JSON 字符串,它就会将 \\ 添加到字符串中,而转换前的原始 JSON 字符串中并不存在该字符串。这发生在每个嵌套字典级别。这些是功能:

import json
import io
import gzip
import base64
import zlib

class numpy_encoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(numpy_encoder, self).default(obj)


def dict_json_dump(dictionary):
    dumped = json.dumps(dictionary, cls = numpy_encoder, separators=(",", ":"))
    return dumped

def gzip_json_encoder(json_string):
    stream = io.BytesIO()
    with gzip.open(filename=stream, mode='wt') as zipfile:
        json.dump(json_string, zipfile)
    return stream

def base64_encoder(gzip_string):
    return base64.b64encode(gzip_string.getvalue())

我们可以使用以下函数:

json_dict = pe.dict_json_dump(test_dictionary)
gzip_json = pe.gzip_json_encoder(json_dict)
base64_gzip = pe.base64_encoder(gzip_json)

当我使用以下函数检查 base64_gzip 时:

json_str = zlib.decompress(base64.b64decode(base64_gzip), 16 + zlib.MAX_WBITS)

我以如下格式返回 JSON 字符串(已截断):

b'"{\\"trainingResults\\":{\\"confusionMatrix\\":{\\"tn\\":2,\\"fn\\":1,\\"tp\\":1,\\"fp\\":1},\\"auc\\":{\\"score\\":0.5,\\"tpr\\":[0.0,0.5,0.5,1.0],\\"fpr\\":[0.0,0.333,0.667,1.0]},\\"f1\\"

这不是完整的字符串,但字符串本身的内容是准确的。我不确定的是为什么当我将其转换回来时会出现反斜杠。有人有什么建议吗?我也尝试对 JSON 进行 utf-8 编码,但没有成功。如有任何帮助,我们将不胜感激!

最佳答案

您将进行两次 JSON 编码:一次在 dict_json_dump() 中,另一次在 gzip_json_encoder() 中。由于 json_string 已经编码,因此不需要在 gzip_json_encoder() 中调用 json.dump()

def gzip_json_encoder(json_string):
    stream = io.BytesIO()
    with gzip.open(filename=stream, mode='wt') as zipfile:
        zipfile.write(json_string)
    return stream

关于python - Gzip 到 base64 编码将字符添加到 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56639107/

相关文章:

python - Dask read_parquet 添加额外的列 dir0

ios - 如何在 SWIFT 3 中使用带有锯齿状数组(json 数据)的 JSONSerialization.jsonObject

python pip : cloudmonkey not installing correctly

python - Polar Matplotlib 图中的箭头

python - 改进Python代码读取文件

python - 如何为Python 2.7重新安装GDAL库?

javascript - 使用 javascript 更新文本框中的值

javascript - 从 JSON 数组中删除行留下 'null'

python-3.x - 在 Python 中使用 pymc 随机化网络

python - 在 centos7 上安装 pip(3) 的推荐方法