Python-AWS Lambda从CloudWatch事件JSON提取字段报错求助
Hey there! Let's break down what's going wrong here and get your function working properly.
The Root Issue
The Message field from your SNS record is a JSON-formatted string, not a native Python dictionary. When you try to access ['Trigger'] directly on this string, Python throws that error because strings only accept numeric indices (like message[0] to grab the first character), not key names.
The Fix
You need to first parse that JSON string into a Python dictionary using json.loads(). Once it's converted, you can access the nested keys normally. Also, keep in mind that Dimensions is likely a list of objects, so you'll need to index into that list before grabbing the name field.
Corrected Code
Here's the updated function with clear comments explaining each step:
import json def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) # Pull the raw JSON string from the SNS message sns_message_str = event['Records'][0]['Sns']['Message'] # Convert the JSON string into a usable Python dictionary sns_message_dict = json.loads(sns_message_str) # Optional: Print the parsed dictionary to confirm the structure matches your expectations print("Parsed SNS message: " + json.dumps(sns_message_dict, indent=2)) # Access the nested 'name' field (use [0] to get the first dimension; adjust if you have multiple) dimension_name = sns_message_dict['Trigger']['Dimensions'][0]['name'] print(f"Extracted dimension name: {dimension_name}") return { 'statusCode': 200, 'body': json.dumps({'extractedDimensionName': dimension_name}) }
Quick Tips
- If your
Dimensionslist has multiple entries, loop through them instead of using[0]to collect allnamevalues. - Use the optional print statement for the parsed dictionary to double-check key names and structure—typos or unexpected nesting are common pitfalls here.
内容的提问来源于stack exchange,提问作者TheDataGuy

