Home > other >  string indices must be integers error when parsing aws sns response
string indices must be integers error when parsing aws sns response

Time:01-15

I have a simple lambda function in python that is being triggered by AWS SNS. This function is simply posting a response on a specific slack channel. Below is the code for that

#!/usr/bin/python3.6
import urllib3
import json
http = urllib3.PoolManager()
def lambda_handler(event, context):
    url = "https://hooks.slack.com/services/dfsrd/B02TM68N97B/8ZjGtfMJNbcCUnUFJzn3DxI8"
    msg = {
        "channel": "#slack-mandrill",
        "username": "WEBHOOK_USERNAME",
        "text": event['Records'][0]['Sns']['Message'],
        "icon_emoji": ""
    }
    
    encoded_msg = json.dumps(msg).encode('utf-8')
    resp = http.request('POST',url, body=encoded_msg)
  print({
        "message": event['Records'][0]['Sns']['Message'], 
        "status_code": resp.status, 
        "response": resp.data
    })

The full response I am getting from the above lambda is like that,

{
  "version": "1.0",
  "timestamp": "2022-01-10T15:21:46.577Z",
  "requestContext": {
    "requestId": "e22f4c5c-6d32-4635-9159-ae1aadf1b4de",
    "functionArn": "arn:aws:lambda:us-east-1:019200159526:function:mandrill:$LATEST",
    "condition": "Success",
    "approximateInvokeCount": 1
  },
  "requestPayload": {
    **"domain": "runstraight.wombang.com"**
  },
  "responseContext": {
    "statusCode": 200,
    "executedVersion": "$LATEST"
  },
  "responsePayload": "success"
}

From above response I just need "domain" value and nothing else. According to JSON structure the below changes should give me the value of domain.

"text": event['Records'][0]['Sns']['Message']['domain']

But after this I am getting the below TypeError. Any idea how to resolve this and get only the domain value? Thanks

"text": event['Records'][0]['Sns']['Message']['requestPayload']['domain'],
TypeError: string indices must be integers

CodePudding user response:

event['Records'][0]['Sns']['Message'] is a JSON string, not a dictionary, so you need to parse it.

def lambda_handler(event, context):
    url = "https://hooks.slack.com/services/dfsrd/B02TM68N97B/8ZjGtfMJNbcCUnUFJzn3DxI8"
    msg = {
        "channel": "#slack-mandrill",
        "username": "WEBHOOK_USERNAME",
        "text": event['Records'][0]['Sns']['Message'],
        "icon_emoji": ""
    }
    
    encoded_msg = json.dumps(msg).encode('utf-8')
    resp = http.request('POST',url, body=encoded_msg)
    message = json.loads(event['Records'][0]['Sns']['Message'])
    print({
        "message": message, 
        "text": message['requestPayload']['domain'],
        "status_code": resp.status, 
        "response": resp.data
    })
  •  Tags:  
  • Related