【问题标题】:Convert a JSON buffer into .gz将 JSON 缓冲区转换为 .gz
【发布时间】:2021-01-26 07:11:51
【问题描述】:

我有以下代码将 pandas 数据帧保存到内存中的 json 中,然后将其加载到 AWS S3:

json_buffer = StringIO()
df.to_json(json_buffer, orient='records', date_format='iso')
json_file_name = file_to_load.split(".")[0] + ".json"
s3_conn.put_object(Body=json_buffer.getvalue(), Bucket=s3_bucket, Key=f"{target_path}{json_file_name}")

我要做的是在将 json 文件放入 S3 存储桶之前将其存档为 gzip (.gz) 格式。 您对如何实现这一目标有任何想法吗?

谢谢!

【问题讨论】:

  • 也许可以尝试使用 compression='gzip' 和 df.to_json

标签: python json pandas amazon-s3 gzip


【解决方案1】:

您可以使用gzip

with gzip.open(json_file_name, 'wt', encoding='UTF-8') as zipfile:
    json.dump(data, zipfile)

这将以 gzip 格式保存 json 文件。所以调用是在传递到 S3 存储桶之前。

【讨论】:

  • 谢谢!所以如果我理解正确的话,'zipfile' 将是现在要加载的文件?
  • @TomerShalhon 这将是压缩版本,但是是的
【解决方案2】:

虽然上面的答案很简单,但如果你在linux kernel 上使用jupyter notebook,那么你可以简单地做

with open("temp.json", 'w') as f:
            f.write(json.dumps(json_data))

! gzip temp.json

upload("bocket_name", "name_of_the_json_file.json.gz", "temp.json.gz")
# def upload(bucket_name, item_name, file_path):

! rm temp.json.gz

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 2022-11-04
    • 2021-01-14
    • 2022-08-05
    • 2020-04-26
    • 2018-06-03
    • 1970-01-01
    • 2018-06-29
    • 2023-03-02
    相关资源
    最近更新 更多