【问题标题】:Python write JSON to S3Python 将 JSON 写入 S3
【发布时间】:2021-09-07 21:06:06
【问题描述】:

这是我需要以 JSON 格式写入 S3 的字典列表。

data = [{"name": "abc", "age": 23}, {"name": "def", "age": 21}, {"name": "fgh", "age": 34}]

我想把它写成example.json,格式如下

{"name": "abc", "age": 23}
{"name": "def", "age": 21}
{"name": "fgh", "age": 34}

因此,将每个 dict 写在一行上并使用 \n 作为换行符。此代码在本地适用于我:

import json
with open('example.json', 'w') as f:
    for d in data:
        json.dump(d, f, ensure_ascii=False)
        f.write('\n')

现在我不想将文件保存在本地,而是直接逐行保存到 S3,或者以任何方式保存所需的格式。我知道我们可以像这样直接使用json.dumps() 写入S3

import json
import boto3

s3 = boto3.client('s3')
s3.put_object(
     Body=str(json.dumps(data))
     Bucket='your_bucket_name'
     Key='your_key_here'
)

但我想保留这不会做的格式。我应该如何继续前进?

【问题讨论】:

    标签: python json python-3.x amazon-s3


    【解决方案1】:

    仅生成字符串并写入 S3 有什么问题吗?

    data_string = ""
    for d in data:
        data_string += json.dumps(d, ensure_ascii=False)
        data_string += "\n"
    
    s3 = boto3.client('s3')
    s3.put_object(
         Body=data_string
         Bucket='your_bucket_name'
         Key='your_key_here'
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 2022-01-24
      • 2020-01-02
      相关资源
      最近更新 更多