我能够使用
将sns事件数据分配给变量def lambda_handler(event, context):
message = event['Records'][0]['Sns']['Message']
print("From SNS: " + message)
输出:
{
"Records": [
{
"eventVersion": "2.0",
"eventSource": "aXXXX",
"awsRegion": "XXXXX",
"eventTime": "2016-03-09T12:24:19.255Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "AWS:XXXXXXXXXXX"
},
"requestParameters": {
"sourceIPAddress": "xxx.xxx.xx.xx"
},
"responseElements": {
"x-amz-request-id": "XXXX",
"x-amz-id-2": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "xxx-xxx-xxx",
"bucket": {
"name": "bucketname",
"ownerIdentity": {
"principalId": "XXXXXX"
},
"arn": "arn:aws:s3:::xxxxx"
},
"object": {
"key": "index.js",
"size": 7068,
"eTag": "xxxx",
"sequencer": "0000000000"
}
}
}
]
}
我无法进一步解析并获取awsRegion
,Records.s3.bucket.name
和Records.s3.object.key
的值。
我试过了bucketname = message['Records'][0]['s3']['bucket']['name']
。
得到错误TypeError:字符串索引必须是整数
答案 0 :(得分:10)
我认为您可能需要加载json:
import json
def lambda_handler(event, context):
message = event['Records'][0]['Sns']['Message']
parsed_message = json.loads(message)
print(parsed_message['Records'][0]['s3']['bucket']['name'])
给我
u'bucketname'
或者你在功能之外的地方做负荷吗?
答案 1 :(得分:0)
我正在尝试在node.js中做同样的事情。我错误地认为该事件正在传递JSON而不是字符串。我加了:
var message = event.Records[0].Sns.Message;
console.log('Message received from SNS:', message);
var bleh=JSON.parse(event.Records[0].Sns.Message);
var blah = bleh.Records[0].s3.bucket.name;
console.log('Bucket Name:', blah);
最终将正确的存储桶名称删除。