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

AWS Lambda报错:list indices must be integers or slices, not str 求助

解决AWS Lambda中"list indices must be integers or slices, not str"错误

错误原因

你的报错核心问题是:代码里直接把metrics当成字典访问,但从你提供的JSON结构能明确看到——metrics是一个列表(数组),列表只能用整数索引或切片访问,不能用字符串'metricStat'作为索引,这就是触发TypeError的根本原因。

修复方法

场景1:metrics仅包含单个元素(匹配你给出的JSON结构)

直接通过索引[0]获取列表中的第一个元素,再逐层访问后续字段:

metricName = event['detail']['configuration']['metrics'][0]['metricStat']['metric']['name']

场景2:metrics可能包含多个元素

如果业务中metrics会有多个项,需要遍历列表逐个处理:

metrics_list = event['detail']['configuration']['metrics']
for metric_item in metrics_list:
    metric_name = metric_item['metricStat']['metric']['name']
    # 此处添加你的业务逻辑,比如打印、存储指标名称等

验证逻辑

修改后代码会先从metrics列表中取出对应字典元素,再依次访问metricStat、metric节点,最终拿到预期的name字段值(如CPUUtilization)。

内容的提问来源于stack exchange,提问作者John Kennedy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:34:58