简体   繁体   English

如何附加到 AWS S3 上的 json 文件

[英]How to append to json file on AWS S3

I need to append to a json file on aws S3, python code is running on an EC2 instance.我需要附加到 aws S3 上的 json 文件,python 代码在 EC2 实例上运行。

In a local setting I can easily do this as follows:在本地设置中,我可以轻松地执行以下操作:

import json

#example data
json_data = {"id": "123", "name": "XYZ", "transaction": [20.0, 30.0]}
# path
local_path = '/home/ubuntu/test.json'

with open(local_path, 'a', encoding='utf-8-sig') as file:
    json.dump(json_data, file)
    file.write('\n')
    file.close()

On EC2 I can connect to S3 as follows:在 EC2 上,我可以按如下方式连接到 S3:

import boto
s3_open = boto.connect_s3(host='s3.eu-central-1.amazonaws.com')

I define the path to S3:我定义了 S3 的路径:

s3_path = 's3://my-bucket/test.json'

How can I append to this file using the logic described above?如何使用上述逻辑附加到此文件?

S3 does not have an append action what you can do is download the file, append it yourself then upload it as a new version of the same object. S3 没有附加操作,您可以做的是下载文件,自己附加,然后将其作为同一对象的新版本上传。

Something along these lines.沿着这些路线的东西。

import json
import boto3

s3_path = '/some/s3/path'
bucket = 'somebucket'
local_data = {"id": "123", "name": "XYZ", "transaction": [20.0, 30.0]}

s3 = boto3.client('s3')
resp=s3.get_object(Bucket=bucket, Key=s3_path)
data=resp.get('Body')

json_data = json.loads(data)
json_data.append(local_data)
s3.put_object(Bucket=bucket, Key=s3_path, Body=json.dumps(json_data).encode())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM