CLAWIST.
📖 指南阅读时间 8 分钟••作者:Lin

使用 Claude 生成结构化输出:JSON 模式及更多技巧

人工智能图形

在使用 Claude 构建应用程序时,你通常需要的是结构化数据,而不是自由格式的文本,也就是可以被解析、验证并在程序中使用的 JSON 响应。本指南将向你展示如何每次都从 Claude 获得可靠的结构化输出。

结构化输出的挑战

默认情况下,Claude 返回的是自然语言。如果你让它 "列出前 5 种编程语言",你可能会得到:

  • 一个编号列表
  • 一个项目符号列表
  • 一段用逗号分隔的文字
  • 一个 JSON 数组(如果你运气好的话)

对于应用程序来说,这种不一致性会导致问题。你需要可预测的结构。

方法一:明确的 JSON 指令

最简单的方法是直接要求 Claude 返回 JSON:

const response = await anthropic.messages.create({
  model: "claude-sonnet-4-20250514",
  max_tokens: 1024,
  messages: [{
    role: "user",
    content: `List the top 5 programming languages by popularity.
    
    Respond with ONLY valid JSON in this format:
    {
      "languages": [
        {"name": "string", "rank": number, "use_case": "string"}
      ]
    }`
  }]
});

这种方法大多数时候都有效。但 Claude 可能会:

  • 在 JSON 前后添加解释性文字
  • 使用略有不同的字段名称
  • 包含你没有要求的额外字段

方法二:通过系统提示强制执行

将 JSON 要求移至系统提示中,以获得一致的行为:

const response = await anthropic.messages.create({
  model: "claude-sonnet-4-20250514",
  max_tokens: 1024,
  system: `You are a JSON API. You ONLY respond with valid JSON.
           Never include explanations, markdown, or text outside the JSON.
           If you cannot fulfill a request, respond with: {"error": "reason"}`,
  messages: [{
    role: "user",
    content: `List top 5 programming languages: 
              {"languages": [{"name": "", "rank": 0, "use_case": ""}]}`
  }]
});

在用户消息中提供确切的模式,相当于给 Claude 提供了一个可遵循的模板。

方法三:JSON 模式(推荐)

Anthropic's API 支持原生 JSON 模式,可保证输出有效的 JSON:

const response = await anthropic.messages.create({
  model: "claude-sonnet-4-20250514",
  max_tokens: 1024,
  messages: [{
    role: "user",
    content: "List the top 5 programming languages with their use cases"
  }],
  response_format: { type: "json_object" }
});

// response.content is guaranteed to be valid JSON
const data = JSON.parse(response.content[0].text);

启用 JSON 模式后:

  • 输出始终是有效的 JSON
  • 没有 Markdown 代码块
  • 没有解释性文字
  • 不再可能出现解析错误

使用 Zod 定义模式

对于 TypeScript 应用程序,请使用 Zod 定义你期望的模式并验证响应:

import { z } from 'zod';

const LanguageSchema = z.object({
  languages: z.array(z.object({
    name: z.string(),
    rank: z.number().int().positive(),
    use_case: z.string(),
    trending: z.boolean().optional()
  }))
});

type LanguageResponse = z.infer<typeof LanguageSchema>;

async function getLanguages(): Promise<LanguageResponse> {
  const response = await anthropic.messages.create({
    model: "claude-sonnet-4-20250514",
    max_tokens: 1024,
    system: `Respond with JSON matching this schema:
             ${JSON.stringify(zodToJsonSchema(LanguageSchema))}`,
    messages: [{
      role: "user", 
      content: "List top 5 programming languages"
    }]
  });
  
  const data = JSON.parse(response.content[0].text);
  return LanguageSchema.parse(data); // Throws if invalid
}

这将为你带来:

  • 代码中的类型安全
  • 运行时验证
  • 模式不匹配时给出清晰的错误信息

处理嵌套结构

复杂的嵌套数据需要清晰的模式定义:

const schema = {
  company: {
    name: "string",
    founded: "number (year)",
    employees: [
      {
        name: "string",
        role: "string",
        department: "string",
        reports_to: "string or null"
      }
    ],
    products: [
      {
        name: "string",
        price: "number",
        features: ["string"]
      }
    ]
  }
};

const response = await anthropic.messages.create({
  model: "claude-sonnet-4-20250514",
  max_tokens: 2048,
  system: `Return JSON matching this exact schema. 
           Use null for unknown values, never omit fields:
           ${JSON.stringify(schema, null, 2)}`,
  messages: [{
    role: "user",
    content: "Generate sample data for a fictional tech startup"
  }]
});

从混合输出中提取 JSON

如果你使用的是较旧的方法,或者 Claude 在 JSON 之外还包含了文本,可以这样提取:

function extractJSON(text) {
  // Try parsing the whole thing first
  try {
    return JSON.parse(text);
  } catch {}
  
  // Look for JSON object
  const objectMatch = text.match(/\{[\s\S]*\}/);
  if (objectMatch) {
    try {
      return JSON.parse(objectMatch[0]);
    } catch {}
  }
  
  // Look for JSON array
  const arrayMatch = text.match(/\[[\s\S]*\]/);
  if (arrayMatch) {
    try {
      return JSON.parse(arrayMatch[0]);
    } catch {}
  }
  
  throw new Error('No valid JSON found in response');
}

这只是一种备用方案——如果可用,请优先使用 JSON 模式。

处理数组和列表

对于列表类的响应,请明确指定数组格式:

// Bad: Ambiguous
"List 5 items"

// Good: Explicit array structure  
"Return a JSON array of exactly 5 objects: [{\"item\": \"...\"}]"

// Better: Full example
`Return JSON in this exact format:
{
  "items": [
    {"name": "Example", "description": "Example description"},
    ...4 more items...
  ],
  "total": 5
}`

错误处理

为生产环境构建健壮的错误处理机制:

async function getStructuredResponse(prompt, schema, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await anthropic.messages.create({
        model: "claude-sonnet-4-20250514",
        max_tokens: 1024,
        response_format: { type: "json_object" },
        messages: [{
          role: "user",
          content: `${prompt}\n\nRespond with JSON matching: ${JSON.stringify(schema)}`
        }]
      });
      
      const data = JSON.parse(response.content[0].text);
      
      // Validate against schema
      if (validateSchema(data, schema)) {
        return data;
      }
      
      // Schema mismatch - retry with more explicit instructions
      console.warn(`Attempt ${attempt + 1}: Schema mismatch, retrying...`);
      
    } catch (error) {
      if (error.status === 429) {
        await sleep(Math.pow(2, attempt) * 1000);
        continue;
      }
      throw error;
    }
  }
  
  throw new Error('Failed to get valid structured response after retries');
}

流式结构化输出

对于较长的响应,可以流式传输 JSON 并增量解析:

import { createParser } from 'streaming-json-parser';

async function streamStructuredResponse(prompt) {
  const parser = createParser();
  
  const stream = await anthropic.messages.create({
    model: "claude-sonnet-4-20250514",
    max_tokens: 4096,
    stream: true,
    response_format: { type: "json_object" },
    messages: [{ role: "user", content: prompt }]
  });
  
  for await (const chunk of stream) {
    if (chunk.type === 'content_block_delta') {
      const partial = parser.write(chunk.delta.text);
      if (partial) {
        // Handle partial object as it's built
        console.log('Partial data:', partial);
      }
    }
  }
  
  return parser.end();
}

最佳实践清单

为了获得可靠的结构化输出:

  1. 使用 JSON 模式 当你的 API 版本支持时
  2. 提供准确的模式 并附上示例值
  3. 在系统提示词中包含模式 以保持一致性
  4. 验证响应 使用 Zod 或 JSON Schema
  5. 处理边缘情况 ——空数组、null 值、缺失字段
  6. 实现重试机制 以应对暂时性故障
  7. 记录解析失败 以便长期改进提示词

结构化输出将 Claude 从一个对话式 AI 转变为一个可编程的 API。掌握这些技巧,你就能构建每次都稳定运行的可靠集成。