以下是一个使用AWS S3和Lambda的示例代码,用于获取、更新和放置JSON文件:
import boto3
import json
def lambda_handler(event, context):
# 获取S3存储桶名称和文件键
bucket_name = event['Records'][0]['s3']['bucket']['name']
file_key = event['Records'][0]['s3']['object']['key']
# 创建S3客户端
s3 = boto3.client('s3')
# 获取JSON文件内容
response = s3.get_object(Bucket=bucket_name, Key=file_key)
json_data = response['Body'].read().decode('utf-8')
json_obj = json.loads(json_data)
# 更新JSON文件内容
json_obj['new_key'] = 'new_value'
updated_json_data = json.dumps(json_obj)
# 将更新后的JSON文件放置回S3存储桶
s3.put_object(Body=updated_json_data.encode('utf-8'), Bucket=bucket_name, Key=file_key)
return {
'statusCode': 200,
'body': json.dumps('JSON file updated successfully')
}
创建一个AWS Lambda函数,将触发器设置为S3,并选择要监视的存储桶和事件类型(例如,ObjectCreated)。
将lambda_function.py代码粘贴到Lambda函数的代码编辑器中。
配置Lambda函数的执行角色,以便具有适当的S3访问权限。
保存和部署Lambda函数。
将一个JSON文件放入所选的S3存储桶中。
当有JSON文件被放置到S3存储桶时,Lambda函数将被触发。它将获取JSON文件的内容,更新文件的内容,然后将更新后的JSON文件放回S3存储桶。你可以根据自己的需求进行修改和扩展这个示例代码。