为什么在 JSON 数据上尝试使用 gzip.compress 时得到 "memoryview: a bytes-like object is required"?

Why do I get "memoryview: a bytes-like object is required" when trying to use gzip.compress on JSON data?

我从 S3 中读取了一个 JSON 文件,如下所示:

json_file = s3_resource.Object(bucket_name='test', key='new.json'
json_content = json.loads(file_content)
....
gzipped_content = gzip.compress(json_content)

将文件读入 json_content 后,我想对其进行 gzip 压缩。

但我不确定要将什么传递给 gzip.compress() 作为参数。

目前,我收到以下错误:

{
  "errorMessage": "memoryview: a bytes-like object is required, not 'list'",
  "errorType": "TypeError",
  "requestId": "017949f4-533b-4087-9038-10fd39f435d9",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 28, in lambda_handler\n    gzipped_content = gzip.compress(json_content)\n",
    "  File \"/var/lang/lib/python3.9/gzip.py\", line 548, in compress\n    f.write(data)\n",
    "  File \"/var/lang/lib/python3.9/gzip.py\", line 284, in write\n    data = memoryview(data)\n"
  ]
}

json_content

[{'actionCodes': [], 'additionalCostOccured': '', 'amountEURRecieved': 0.0, 'amountOfAdditionalCost':}]

对于压缩文件,我做了类似的事情并且有效:

     with zipped.open(file, "r") as f_in:
           gzipped_content = gzip.compress(f_in.read())

有什么问题?

如错误所示,gzip.compress(...) 期望 bytes-like object,而您提供 list.

您需要:

  1. 将(修改过的?)list 对象(或任何其他 JSON 规范兼容对象)传递给 json.dumps 以获得 JSON格式化 str

  2. 将JSON字符串传递给str.encode to then get a bytes对象

  3. bytes 对象传递给 gzip.compress(...)

这应该有效:

json_file = s3_resource.Object(bucket_name='test', key='new.json'
json_content = json.loads(file_content)
....
content_back_to_json = json.dumps(json_content)
json_content_as_bytes = str.encode(content_back_to_json)
gzipped_content = gzip.compress(json_content_as_bytes)