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

Colab中调用API获取列表后添加元素遇JSONDecodeError问题

解决JSONDecodeError:API返回含多余文本的列表字符串解析问题

问题原因

你的代码报错源于两个核心问题:

  1. API返回的response并非纯JSON格式,包含了多余的说明文本(比如开头的"The teams in the match..."段落),json.loads()从字符串起始位置无法识别有效JSON结构。
  2. 返回的列表使用了单引号,而JSON规范要求字符串必须用双引号包裹,这也会导致解析失败。

解决方法

方法1:清洗现有返回内容后解析

通过字符串处理提取出纯列表部分,再转换为符合JSON要求的格式:

import json

# 提取response中的列表片段(从第一个[到最后一个])
start_pos = response.find('[')
end_pos = response.rfind(']')
raw_list_str = response[start_pos:end_pos + 1]

# 将单引号替换为双引号,符合JSON格式
valid_json_str = raw_list_str.replace("'", '"')

# 解析并添加额外元素
CLASSES = json.loads(valid_json_str) + ["none"]
print(CLASSES)

方法2:优化Prompt从源头避免问题

修改Prompt,明确要求API只返回纯JSON格式的列表,不要任何额外说明:

prompt = (
    "What colors of uniforms are worn by the teams playing in this match?",
    "ONLY return a valid JSON list of color strings. No explanations, no extra text.",
    "Use double quotes for all strings, example: [\"orange\", \"white\"]"
)
response = prompt_image(api_key=OPENAI_API_KEY, images=[frame], prompt=prompt)

# 直接解析并添加元素
CLASSES = json.loads(response) + ["none"]

补充说明

如果print(response)看起来只输出了列表,大概率是输出时的换行或截断导致你没看到前面的说明文本,可以用print(repr(response))查看response的原始完整内容,确认是否包含多余字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 23:47:23