【发布时间】:2019-06-17 21:25:17
【问题描述】:
我有一个嵌套的 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 编码,但没有运气。任何帮助表示赞赏!
【问题讨论】:
标签: python json python-3.x base64 gzip