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

在Django中调用Stability AI SVD API时遇JSONDecodeError求排查修复

Django调用Stability AI SVD API触发JSONDecodeError错误

错误说明

调用Stability AI的图生视频(SVD)API时,抛出JSONDecodeError: Extra data: line 1 column 5 (char4)错误,无法正常解析API返回内容。

错误原因

  1. 响应内容不是合法单一JSON:错误核心是json.loads()要解析的内容包含多余数据——可能是多个独立JSON对象拼接,或者开头/结尾混了非JSON字符(比如空格、换行、HTML代码)。比如API请求出错时,可能返回HTML格式的错误页面而非JSON,直接解析就会触发异常。
  2. API返回流式响应:部分生成类API会采用流式输出,每行返回一个JSON对象,直接用json.loads()解析整个响应内容就会触发“多余数据”错误。
  3. 请求参数/头信息错误:如果请求的Accept头设置不当,或者参数不符合API要求,API可能返回非JSON格式内容,导致解析失败。

修复方案

1. 先校验响应格式再解析

用requests内置的json()方法替代json.loads(),它会自动处理编码和格式校验,同时提前检查响应的Content-Type:

response = requests.post(api_url, headers=headers, files=files, data=data)
# 先确认响应是JSON格式
if 'application/json' in response.headers.get('Content-Type', ''):
    try:
        response_data = response.json()
        # 后续业务逻辑
    except json.JSONDecodeError:
        # 打印原始响应内容排查问题
        print('响应内容非合法JSON:', response.text)
else:
    print('API返回非JSON内容:', response.text)

2. 处理流式响应

如果API是流式输出(比如逐行返回JSON),改成逐行解析:

# 请求时开启流式模式
response = requests.post(api_url, headers=headers, files=files, data=data, stream=True)
for line in response.iter_lines():
    if line:  # 跳过空行
        try:
            line_data = json.loads(line)
            # 处理单条JSON数据
        except json.JSONDecodeError:
            print('单行解析失败:', line.decode('utf-8'))

3. 检查请求参数和头信息

  • 确认Authorization头格式正确:Bearer 你的API密钥(注意Bearer后面有空格)
  • 检查上传的图片格式是否符合要求(支持PNG、JPG,文件大小合规)
  • 核对motion_bucket_id、cfg_scale等参数是否在API允许的范围内
  • 把Accept头设为application/json, text/plain,兼容不同类型的响应

4. 捕获错误并输出完整响应

在代码里增加错误捕获,打印原始响应内容,方便定位问题:

try:
    response_data = json.loads(response.content)
except json.JSONDecodeError as e:
    print(f'解析错误详情: {e}')
    print(f'完整响应内容: {response.content.decode("utf-8", errors="replace")}')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 19:41:11