SageMaker端点通过Lambda推理触发JSONDecodeError问题求助
根因定位
你遇到的JSONDecodeError核心原因是SageMaker端点返回的推理结果不是合法JSON格式,你当前分类模型的输出是纯字符串/CSV格式文本,和之前返回JSON结构的优先级预测模型输出格式不一致,导致json.loads()无法解析。
排查步骤
首先在Lambda中添加日志打印端点的原始返回内容,确认输出格式:
def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) data = json.loads(json.dumps(event)) payload = data['data'] print(payload) response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME, ContentType='text/csv', Body=payload) # 新增:先保存原始响应,避免流读取一次后为空 raw_response = response['Body'].read().decode().strip() print("SageMaker端点原始返回内容:", raw_response) # 查看CloudWatch日志确认格式 # 临时注释原json解析代码,先确认返回格式 # result = json.loads(raw_response) return {"raw_response": raw_response}
部署后重新发送请求,到Lambda对应的CloudWatch日志组查看raw_response的实际内容。
修复方案
根据返回内容的不同,对应调整解析逻辑:
情况1:端点返回纯分类字符串(如直接返回Hardware)
不需要用JSON解析,直接构造返回结构即可:
raw_response = response['Body'].read().decode().strip() result = {"category": raw_response} return result
情况2:端点返回CSV格式内容(如返回Hardware,0.95,包含分类和置信度)
用csv模块解析即可:
import csv from io import StringIO raw_response = response['Body'].read().decode().strip() reader = csv.reader(StringIO(raw_response)) category, confidence = next(reader) result = {"category": category, "confidence": float(confidence)} return result
可选:对齐模型输出格式
如果希望统一解析逻辑,可以调整分类模型的推理代码,和优先级模型一样输出JSON格式的结果,这样不需要修改Lambda解析逻辑。
内容的提问来源于stack exchange,提问作者user203818
相关产品推荐
相关产品推荐

