如何在 json 中转储压缩字符串?

How to dump compressed strings in json?

我有一个正在使用 zlib 压缩的字符串,将其存储在字典中并创建字典的 md5 散列。但我收到错误:

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 1: invalid start byte

密码是:

data['extras'] = zlib.compress("My string".encode("utf-8"))  //The string is very large that\'s why it\'s needed to be compressed to save up memory 
checkup['hash'] = hashlib.md5(json.dumps(dict(data), sort_keys=True)).hexdigest()

字典是这样的:

{'extras':'x\x9cK\x04\x00\x00b\x00b'}

谁能告诉我如何将这个 dictionary/string 转储到 JSON 中?

字符串很长json。类似于:

{
    "listing": {
            "policies": null,
            "policy_explanation": "Some Text",
            "policy_name": "Flexi3",
            "updated": "7 weeks ago",
            "city": "Bengaluru",
            "country": "India",
             .
             .
             .   
}

您可以先对其进行 base64 编码,使其正常工作。它会增加一些字符串的大小,但可能比你先压缩它保存的要少:

data['extras'] = base64.b64encode(zlib.compress("My string".encode("utf-8")))