跳转到正文Baichentoken
控制台

json输出

本页介绍如何使用 Gemini 原生格式生成结构化 JSON 输出。你可以通过 generationConfig 指定响应 MIME 类型和 JSON Schema,让模型按照固定结构返回内容。

请求地址

https://api.e6t.cn/v1beta/models/{model}:generateContent

Python 示例代码

下面示例让模型列出几种流行的中国早餐,并按照指定 JSON Schema 返回早餐名称和配料信息。

"""
Baichentoken Gemini JSON 模式测试脚本

功能:
使用 Gemini API 生成结构化 JSON 响应。
示例:获取中国流行早餐及其配料信息。
"""

import json
import requests


# ==================== API 配置 ====================

api_key = "sk-*****************************************"
model = "gemini-2.5-flash"
url = f"https://api.e6t.cn/v1beta/models/{model}:generateContent?key={api_key}"


# ==================== 请求数据 ====================

payload = {
    "contents": [
        {
            "role": "user",
            "parts": [
                {
                    "text": "请列出几种流行的中国早餐,并包含配料的用量。"
                }
            ]
        }
    ],
    "generationConfig": {
        "responseMimeType": "application/json",
        "responseSchema": {
            "type": "ARRAY",
            "items": {
                "type": "OBJECT",
                "properties": {
                    "recipeName": {
                        "type": "STRING"
                    },
                    "ingredients": {
                        "type": "ARRAY",
                        "items": {
                            "type": "STRING"
                        }
                    }
                },
                "propertyOrdering": ["recipeName", "ingredients"]
            }
        }
    }
}


# ==================== 发送请求 ====================

headers = {
    "Content-Type": "application/json"
}

response = requests.post(
    url,
    headers=headers,
    data=json.dumps(payload)
)

print(response.text)

返回示例

Gemini 返回结果中,结构化 JSON 通常位于 candidates[0].content.parts[0].text:

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "[\n  {\n    \"recipeName\": \"豆浆油条\",\n    \"ingredients\": [\n      \"豆浆: 200ml\",\n      \"油条: 1根\",\n      \"白糖: 适量\"\n    ]\n  },\n  {\n    \"recipeName\": \"皮蛋瘦肉粥\",\n    \"ingredients\": [\n      \"大米: 1/2杯\",\n      \"清水: 6-8杯\",\n      \"猪瘦肉: 100克\",\n      \"皮蛋: 1-2个\"\n    ]\n  }\n]"
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 28,
    "candidatesTokenCount": 668,
    "totalTokenCount": 2285
  },
  "modelVersion": "gemini-2.5-flash",
  "responseId": "example-response-id"
}

读取 JSON 文本

result = response.json()
json_text = result["candidates"][0]["content"]["parts"][0]["text"]
data = json.loads(json_text)

print(data)

关键参数说明

参数说明
responseMimeType指定响应格式。JSON 输出时设置为 application/json。
responseSchema定义返回 JSON 的结构。
typeSchema 类型,例如 ARRAY、OBJECT、STRING。
properties对象字段定义。
propertyOrdering字段输出顺序。

注意事项

  • 请将示例中的 sk-***************************************** 替换为你的真实 API Key。
  • JSON 输出仍然在模型文本字段中返回,业务代码中建议使用 json.loads() 二次解析。
  • Schema 越清晰,输出越稳定。
  • 对强校验业务,建议服务端再次校验字段类型和必填字段。

On this page