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

如何让Google Gemini-Pro-Vision返回指定结构JSON及处理非JSON响应

解决Google Gemini-Pro-Vision响应转标准JSON的问题

一、从源头规范输出(最优方案)

直接在请求Gemini的提示词中明确要求返回严格符合指定格式的纯JSON字符串,禁止添加任何额外说明、注释或冗余文本。示例提示词如下:

分析图片内容,返回严格遵循以下格式的JSON字符串,不要包含任何额外内容:
{
"Title": "",
"Description": "",
"Category": "",
"Subcategory": "",
"EstimatedPrice": ""
}

这种方式能从根本上避免后续的字符串解析问题,是最可靠的解决方案。

二、已获取非标准响应时的处理方法

如果已经拿到了带冗余内容的响应字符串,可通过以下方式提取并转换为标准JSON:

1. 精准切片提取JSON部分

若响应仅在JSON前后包裹了无关文本,直接定位JSON的首尾符号({和})进行截取:

import json

# 示例Gemini返回的非标准响应
gemini_response = "图片分析结果:{\"Title\": \"chair\",\"Description\": \"A wooden chair with wheels\",\"Category\": \"Furniture\",\"Subcategory\": \"office stuff\",\"EstimatedPrice\": \"$10 - 20 \"}分析结束"

# 提取JSON片段
start_pos = gemini_response.find('{')
end_pos = gemini_response.rfind('}') + 1
json_content = gemini_response[start_pos:end_pos]

# 反序列化JSON
try:
    parsed_data = json.loads(json_content)
    print(parsed_data)
except json.JSONDecodeError as err:
    print(f"解析失败:{err}")

2. 正则表达式匹配完整JSON结构

如果响应中包含换行、零散注释等复杂格式,用正则表达式匹配完整的JSON对象:

import json
import re

# 示例带换行和冗余文本的响应
gemini_response = "以下是图片分析:\n{\n\"Title\": \"chair\",\n\"Description\": \"A wooden chair with wheels\",\n\"Category\": \"Furniture\",\n\"Subcategory\": \"office stuff\",\n\"EstimatedPrice\": \"$10 - 20 \"\n}\n完成分析"

# 匹配JSON对象的正则(DOTALL模式允许匹配换行)
json_pattern = re.compile(r'\{.*?\}', re.DOTALL)
match_result = json_pattern.search(gemini_response)

if match_result:
    json_content = match_result.group()
    try:
        parsed_data = json.loads(json_content)
        print(parsed_data)
    except json.JSONDecodeError as err:
        print(f"解析失败:{err}")
else:
    print("未在响应中找到有效JSON结构")

3. 修复格式瑕疵后解析

若Gemini返回的JSON存在小格式问题(比如用单引号代替双引号、键未加引号),先修正格式再解析:

import json
import re

# 示例格式有瑕疵的响应
gemini_response = "{Title: 'chair', Description: 'A wooden chair with wheels', Category: 'Furniture', Subcategory: 'office stuff', EstimatedPrice: '$10 - 20 '}"

# 修正格式:给未加引号的键添加双引号,替换单引号为双引号
fixed_json = re.sub(r'(\w+):', r'"\1":', gemini_response)
fixed_json = fixed_json.replace("'", "\"")

try:
    parsed_data = json.loads(fixed_json)
    print(parsed_data)
except json.JSONDecodeError as err:
    print(f"解析失败:{err}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 03:19:57