SupaStore

返回博客列表

Claude 结构化输出怎么用?让 Claude API 稳定返回 JSON 的 3 种方法(2026)

Claude 结构化输出怎么用?本文介绍让 Claude API 稳定返回 JSON 的 3 种方法:output_config.format 的 json_schema 写法、Python SDK 的 messages.parse 搭配 Pydantic、工具调用的 strict 严格模式,说明支持的 JSON Schema 特性和限制,并对比提示词约束 JSON 的常见问题。

SupaStore 开发者体验组 ·

Claude 结构化输出怎么用?让 Claude API 稳定返回 JSON 的 3 种方法(2026)

Claude 结构化输出(Structured Outputs)让 Claude API 按你给的 JSON Schema 返回结果,输出一定是合法、可解析的 JSON。以前只能在提示词里写"请只返回 JSON",再祈祷模型别多说一句话、别漏字段;用了结构化输出,就不再需要在代码里写一堆容错和重试。

本文介绍让 Claude 稳定返回 JSON 的 3 种方法,说明 JSON Schema 支持哪些特性、有哪些限制,以及什么时候用哪种方法。基础调用方法见《Claude API 调用教程:Python 接入 Claude API 完整示例》。


为什么需要 Claude 结构化输出

只靠提示词约束 JSON,常见这些问题:

  • 输出前后多了"好的,以下是结果:"之类的说明文字;
  • 漏掉必填字段,或者字段名大小写不一致;
  • 类型不对,数字被写成了字符串;
  • 偶尔输出被 Markdown 代码块包住,直接 json.loads 报错。

另外,新一代 Claude 模型已经不支持预填充(在助手消息开头写一个 { 引导输出),传入会返回 400。结构化输出是官方推荐的替代方案。

支持结构化输出的模型

Fable 5.1、Opus 5.5、Sonnet 5.5、Haiku 5.5 等当前主力模型都支持,Opus 5、Sonnet 5、Haiku 4.5 等上一代模型也支持。各模型的区别见《Claude Opus 和 Sonnet 有什么区别?2026 Claude 模型对比与选型指南》。


方法一:output_config.format 指定 JSON Schema

在 messages.create 中传入 output_config.format,类型为 json_schema:

import json
import anthropic

client = anthropic.Anthropic(base_url="https://api.supastore.cc/v1")

response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=16000,
    messages=[{
        "role": "user",
        "content": "提取信息:张三([email protected])想购买企业版,并希望预约演示。",
    }],
    output_config={
        "format": {
            "type": "json_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "email": {"type": "string"},
                    "plan": {"type": "string"},
                    "demo_requested": {"type": "boolean"},
                },
                "required": ["name", "email", "plan", "demo_requested"],
                "additionalProperties": False,
            },
        }
    },
)

text = next(b.text for b in response.content if b.type == "text")
data = json.loads(text)
print(data["name"], data["demo_requested"])

设置了 output_config.format 后,返回的文本块一定是符合 Schema 的合法 JSON。注意参数名是 output_config.format,旧的 output_format 参数已经不推荐直接用于 messages.create。


方法二:messages.parse 搭配 Pydantic(推荐)

Python 项目最省事的写法是用 Pydantic 定义数据结构,交给 messages.parse,SDK 会自动生成 Schema 并校验结果:

from typing import List
from pydantic import BaseModel
import anthropic

class ContactInfo(BaseModel):
    name: str
    email: str
    plan: str
    interests: List[str]
    demo_requested: bool

client = anthropic.Anthropic(base_url="https://api.supastore.cc/v1")

response = client.messages.parse(
    model="claude-sonnet-5-5",
    max_tokens=16000,
    messages=[{
        "role": "user",
        "content": "提取信息:李四([email protected])想要企业版,对 API 和 SDK 感兴趣,需要演示。",
    }],
    output_format=ContactInfo,
)

contact = response.parsed_output  # 已校验的 ContactInfo 实例
print(contact.name, contact.interests)

response.parsed_output 直接就是 Pydantic 对象,不用再手动 json.loads 和校验类型。


方法三:工具调用的 strict 严格模式

如果你要的不是"回复本身是 JSON",而是"Claude 调用工具时的参数一定合法",就在工具定义里加 "strict": True:

tools = [{
    "name": "create_ticket",
    "description": "创建客服工单。用户反馈问题需要跟进时调用。",
    "strict": True,
    "input_schema": {
        "type": "object",
        "properties": {
            "title": {"type": "string"},
            "priority": {"type": "string", "enum": ["low", "medium", "high"]},
            "tags": {"type": "array", "items": {"type": "string"}},
        },
        "required": ["title", "priority", "tags"],
        "additionalProperties": False,
    },
}]

工具调用的完整流程见《Claude 工具调用怎么用?Claude Function Calling 教程》。两种方式也可以在同一个请求里同时使用:工具参数用 strict 保证,最终回复用 output_config.format 约束。

3 种方法怎么选

需求 推荐方法
从文本中提取信息、分类、打标签,直接要 JSON 结果 output_config.format 或 messages.parse
Python 项目,希望自动校验并拿到对象 messages.parse + Pydantic
Claude 需要调用你的函数,且参数必须合法 工具的 strict: true

JSON Schema 支持什么、不支持什么

支持 不支持
基本类型:object、array、string、integer、number、boolean、null 递归 Schema
enum、const、anyOf、allOf、$ref / $def 数值约束:minimum、maximum、multipleOf
字符串格式:date-time、date、email、uri、uuid 等 字符串长度约束:minLength、maxLength
additionalProperties: false(所有对象都必须设置) 复杂的数组约束,additionalProperties 设为 false 以外的值

Python 和 TypeScript SDK 会自动把不支持的约束从发给 API 的 Schema 中移除,改为在客户端校验。


使用 Claude 结构化输出的注意事项

  1. 首次请求稍慢:新 Schema 第一次使用时需要编译,之后 24 小时内相同 Schema 会复用缓存;
  2. 检查 stop_reason:max_tokens 表示输出被截断,JSON 可能不完整,需要调大 max_tokens;refusal 表示模型拒绝回答,输出可能不符合 Schema;
  3. 不能与引用(Citations)同时使用,否则返回 400;
  4. 可以和批处理、流式输出、Token 计数、思考功能一起用。大批量提取任务配合 Batch API 还能再省一半,见《Claude Batch API 怎么用?》;
  5. Schema 保持稳定:Schema 会进入请求内容,频繁变动不利于命中 Prompt 缓存。

通过中转站调用时,要确认服务商完整透传 output_config 字段,可以先发一条简单请求,检查返回的是不是纯 JSON。相关报错的排查方法见《Claude API 报错怎么办?2026 Claude API 错误码大全》。


常见问题 (FAQ)

Q: Claude API 怎么返回 JSON 格式?

答: 在请求中设置 output_config.format,类型为 json_schema 并提供 Schema,Claude 返回的文本就一定是符合 Schema 的合法 JSON;Python 项目也可以用 messages.parse 搭配 Pydantic 模型。

Q: Claude 结构化输出支持哪些模型?

答: Fable 5.1、Opus 5.5、Sonnet 5.5、Haiku 5.5 等当前主力模型都支持,Opus 5、Sonnet 5、Haiku 4.5 等上一代模型也支持结构化输出。

Q: 为什么设置了结构化输出还是解析失败?

答: 先检查 stop_reason,如果是 max_tokens 说明输出被截断,需要调大 max_tokens;如果是 refusal 说明模型拒绝了请求,此时输出可能不符合 Schema。

Q: JSON Schema 里能用 minLength 和 maximum 吗?

答: API 本身不支持字符串长度和数值范围约束,Python 和 TypeScript SDK 会自动把这些约束移出发给 API 的 Schema,改为在客户端校验。

Q: 新模型还能用预填充让 Claude 输出 JSON 吗?

答: 不能,Claude 4.6 及之后的模型不支持助手消息预填充,传入会返回 400,官方推荐改用结构化输出 output_config.format。