解析AWS Lamdba JSON

时间:2019-09-24 06:19:30

标签: python amazon-web-services aws-lambda

我有一个返回以下内容的AWS Lambda函数:

{'Records': [{'EventSource': 'aws:sns', 'EventVersion': '1.0', 
'EventSubscriptionArn': 'deleted', 'Sns': {'Type': 'Notification', 'MessageId': 
'ID', 'TopicArn': 'deleted', 'Subject': None, 'Message': '{"addressLength":
{"NULL":true},"lName":{"NULL":true},"zipCode":{"NULL":true},"loanType":
{"S":"Car"},"city":{"NULL":true},"birthDate":{"NULL":true},"loanAmount":
{"N":"100000"},"ssn":{"NULL":true},"emailAddress":
{"S":"test@testerson.com"},"fName":{"S":"Testy"},"phoneNumber":
{"S":"2220009999"},"streetAddress":{"NULL":true},"LoanBotTableId":
{"S":"85863390"},"state":{"NULL":true}}', 'Timestamp': '2019-09-
24T06:09:37.025Z', 'SignatureVersion': '1', 'Signature': 'deleted',
 'SigningCertUrl': 'URL', 'UnsubscribeUrl': 'URL', 'MessageAttributes': {}}}]}

我正在尝试获取消息信息。 当我使用Message = event['Records'][0]['Sns']['Message']

我得到:

{
    "addressLength": {
        "NULL": true
    },
    "lName": {
        "NULL": true
    },
    "zipCode": {
        "NULL": true
    },
    "loanType": {
        "S": "Car"
    },
    "city": {
        "NULL": true
    },
    "birthDate": {
        "NULL": true
    },
    "loanAmount": {
        "N": "9000"
    },
    "ssn": {
        "NULL": true
    },
    "emailAddress": {
        "S": "had@g.com"
    },
    "fName": {
        "S": "haad"
    },
    "phoneNumber": {
        "S": "9099999999"
    },
    "streetAddress": {
        "NULL": true
    },
    "LoanBotTableId": {
        "S": "39765985"
    },
    "state": {
        "NULL": true
    }
}

当我使用

Message = event['Records'][0]['Sns']['Message']['phoneNumber']['S']

我得到

  

[ERROR] TypeError:字符串索引必须为整数

有人可以帮助我获取信息吗?

1 个答案:

答案 0 :(得分:2)

您收到的错误是由于Message = event['Records'][0]['Sns']['Message']是一个字符串,但是您尝试访问phoneNumber键,因此出现了错误。

首先,您应该解析json,然后访问数据:

message = event['Records'][0]['Sns']['Message']
parsed_message = json.loads(message)
phone_number = parsed_message['phoneNumber']['S']