
`gr.Number` outputs in `gr.Examples` crash with `JSONDecodeError` when the cached value is negative
快速结论:当 `gr.Examples` 的输出组件为 `gr.Number` 且缓存值为负数时,点击示例会崩溃,报 `JSONDecodeError`。优先排查 `log.csv` 中负数的存储格式是否被添加了前导单引号 `’`。
问题场景
用户在 Gradio 应用中使用 `gr.Interface` 配合 `gr.Examples` 和 `cache_examples=True`,且输出为 `gr.Number` 类型时触发。当函数返回负数(如 `-0.5678` 或 `-42`),点击示例会出现崩溃。
报错原文
File ".../gradio/helpers.py", line 618, in load_from_cache
output.append(component.read_from_flag(value_to_use))
File ".../gradio/components/number.py", line 178, in read_from_flag
return json.loads(payload)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
原因分析
Gradio 的 CSV 防注入函数 sanitize_value_for_csv(位于 gradio/utils.py)会为任何以不安全前缀(如 -、=、+、@ 等)开头的字符串添加前导 '。因此,Number.flag() 调用 json.dumps(-0.5678) 得到 "-0.5678",但在写入 log.csv 时被转换为 '-0.5678。读取时,read_from_flag 将原始 CSV 单元格内容直接传入 json.loads,导致 ' 字符引发解析错误。
环境排查
- Gradio 版本:优先确认是否为 6.19.0(Issue 中使用的版本)
- 确认是否启用了
cache_examples=True - 检查
log.csv文件中负数的存储格式,看是否有前导单引号
解决步骤
- 打开文件
gradio/components/number.py(在 Gradio 安装目录下,例如site-packages/gradio/components/number.py)。 - 定位到
read_from_flag方法(大约在第 178 行)。 - 在该方法中,添加对前导单引号的处理:
- 如果
payload是字符串且以'开头,则去掉该字符后再交给json.loads解析。
验证方法
使用以下场景测试:函数返回负数(如 -0.5678),点击示例后不再崩溃,且输出正确显示为负数。此外,正数(如 0.5678)应继续正常工作。
![[RFC]: Opt-in Media URL Cache for `MediaConnector`](https://www.chat-gpts.plus/wp-content/uploads/2026/07/37075-315181f6-768x403.jpg)

