通过API Gateway与Postman调用Lambda时,如何正确解析POST的JSON数据?
解决API Gateway触发Lambda时无法提取POST JSON数据的问题
问题根源
通过AWS控制台测试Lambda时,你输入的JSON会直接作为event参数传入,所以原代码能正常读取inv_event['data'];但通过API Gateway触发时,Lambda收到的event是API Gateway封装后的请求结构,你发送的JSON数据被放在event['body']字段中,且是字符串类型,直接尝试读取inv_event['data']自然会报错TypeError: string indices must be integers。
解决方案
你需要先从event中提取body字段的字符串,再用json.loads()解析成JSON对象,之后再读取需要的字段。修改后的代码如下:
import json def lambda_handler(event, context): # 从event中获取POST的JSON字符串 request_body = event['body'] # 解析字符串为JSON对象 inv_event = json.loads(request_body) # 读取invoiceId invoiceId = inv_event['data']['invoice']['invoiceId'] # 后续业务逻辑... return { 'statusCode': 200, 'body': json.dumps({'invoiceId': invoiceId}) }
额外注意事项
如果API Gateway配置了Base64编码(event['isBase64Encoded']为true),需要先对body进行Base64解码,再解析JSON:
import base64 import json def lambda_handler(event, context): request_body = event['body'] if event['isBase64Encoded']: request_body = base64.b64decode(request_body).decode('utf-8') inv_event = json.loads(request_body) invoiceId = inv_event['data']['invoice']['invoiceId'] # 后续业务逻辑...
内容的提问来源于stack exchange,提问作者user12073359
相关产品推荐
相关产品推荐

