我從 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())
問題是什么?
uj5u.com熱心網友回復:
正如錯誤所暗示的那樣,gzip.compress(...)需要一個類似位元組的 object,而您提供的是list.
你需要:
傳遞(修改?)
list物件(或任何其他 JSON 規范兼容物件)json.dumps以獲得 JSON 格式str將 JSON 字串傳遞
str.encode給然后獲取一個bytes物件將
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/352688.html
標籤:Python json 蟒蛇-3.x 亚马逊-s3 压缩包
