I was able to assign the sns event data to a variable using
def lambda_handler(event, context):
    message = event['Records'][0]['Sns']['Message']
    print("From SNS: " + message)
Output :
{
    "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"
                }
            }
        }
    ]
}
I am unable to further parse and get the values of awsRegion, Records.s3.bucket.name and Records.s3.object.key.
I have tried bucketname = message['Records'][0]['s3']['bucket']['name'].
getting the error TypeError: string indices must be integers
If you have a JSON string, you can parse it by using the json. loads() method. The result will be a Python dictionary.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
I think you may need to load the 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'])
Gives me
u'bucketname'
Or are you doing the loads somewhere outside your function?
I'm trying to do the same thing in node.js. I mistakenly assumed the event was passing JSON and not a string. I added:
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);
which finally kicked out the right bucket name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With