You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python-AWS Lambda从CloudWatch事件JSON提取字段报错求助

Fixing "TypeError: string indices must be integers" in Your Lambda Function

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 Dimensions list has multiple entries, loop through them instead of using [0] to collect all name values.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:34:24