Parsing json data for aws sns event data in python

I managed 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 can not continue the parsing and get the values awsRegion, Records.s3.bucket.nameand Records.s3.object.key.

I have tried bucketname = message['Records'][0]['s3']['bucket']['name']. getting TypeError error: string indices must be integers

+4
source share
1 answer

I think you may need to download 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 loads somewhere outside of your function?

+7
source

All Articles