解析AWS Cognito导出JSON提取邮箱报string indices must be integers错误
问题根因
expected_value本身已经是JSON格式字符串,你额外调用json.dumps()会将字符串再次序列化,导致后续json.loads()解析后得到的依然是字符串类型,而非预期的Python字典。字符串只能用整数下标索引,你用['Users']这种键名索引自然抛出string indices must be integers错误。
修复代码
基础修复(可正常取到第一个邮箱)
import json def lambda_handler(event, context): # 直接解析原始JSON字符串即可,无需先dumps y = json.loads(expected_value) email = y['Users'][0]['Attributes'][0]['Value']
完整实现(提取所有邮箱)
如果要提取全部用户的所有邮箱,同时适配字段位置不固定的场景,可增加邮箱格式校验:
import json import re # 邮箱格式正则校验 EMAIL_RULE = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$') def lambda_handler(event, context): user_data = json.loads(expected_value) all_emails = [] # 遍历所有用户 for user in user_data.get('Users', []): # 遍历用户所有属性 for attr in user.get('Attributes', []): attr_val = attr.get('Value', '').strip() # 校验值是否为邮箱 if EMAIL_RULE.match(attr_val): all_emails.append(attr_val) return all_emails
验证方式
你可以添加如下打印代码确认类型问题:
data = json.dumps(expected_value) y = json.loads(data) print(type(y)) # 输出为 <class 'str'>,确认解析后不是字典
内容的提问来源于stack exchange,提问作者L44TXF
相关产品推荐
相关产品推荐

