我有一个嵌套的 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/