Skip to content

JSON 输出

通过 response_format: { "type": "json_object" } 让模型返回 JSON。

请求示例

bash
curl https://api.aiqizhilian.tech/v1/chat/completions \
  -H "Authorization: Bearer <你的 API Key>" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.5",
    "messages": [
      {
        "role": "system",
        "content": "你必须只输出合法 JSON,不要输出 Markdown。"
      },
      {
        "role": "user",
        "content": "返回一个 JSON,包含 status=ok 和 message=success。"
      }
    ],
    "max_tokens": 256,
    "response_format": {
      "type": "json_object"
    }
  }'

模型支持情况

强 JSON 输出推荐

  • gpt-5.5
  • gpt-5.4
  • glm-5.1
  • qwen3.6-max-preview
  • qwen3.6-plus
  • deepseek-v4-pro
  • deepseek-v4-flash
  • kimi-k2.6

这些模型在 response_format: json_object 下会返回裸 JSON,可直接 JSON.parse / json.loads

需要客户端兜底

Claude 系列(claude-opus-4-7 / claude-opus-4-6 / claude-sonnet-4-6 / claude-haiku-4-5-20251001)和 Gemini 系列接受 response_format,但可能返回被 Markdown code fence 包裹的 JSON:

text
```json
{ "status": "ok" }

客户端需要在 parse 之前去掉 ` ```json ... ``` ` 外壳。

生产建议

  • 强结构化场景建议在服务端做 JSON parse 失败兜底(捕获异常 + 重试)。
  • 对 schema 严格的场景,加 schema 校验(如 jsonschemazodpydantic),不通过则重试或回退到关键词解析。
  • 不要假设模型每次都会返回完全合法 JSON。
  • 提示词中明确说明 "只输出 JSON,不要包含 Markdown 代码块、解释文字或前后空行",能显著降低出错率。