JSON 結構化輸出提示詞 — 精準控制 Claude 輸出格式
當 Claude 輸出可編程的 JSON 時,你才能真正整合 AI 到自動化流程中。但讓 LLM 輸出可靠的、有效的 JSON並非易事。本指南涵蓋如何設計 JSON schema、驗證規則、處理邊界情況,以及五個實戰案例。
1. 為什麼 JSON 輸出很難?
Claude 是文本生成器,不是 JSON 序列化器。常見的問題:
- 語法錯誤:缺少逗號、雙引號、括號不匹配
- 類型錯誤:字符串當數字、數組當對象
- 格式不一致:有時是 snake_case,有時 camelCase
- 包含雜亂文本:JSON 前後有「讓我幫你」之類的文字
- 字段遺漏:無法確認所有必需字段都存在
解決方案的層次:
- 明確定義 schema(第 1 級)
- 提供 JSON 範例(第 2 級)
- 明確驗證規則(第 3 級)
- Post-processing 驗證(第 4 級)
2. 第一級:明確 JSON Schema
❌ 含糊的指令
Return the data as JSON with relevant fields.
✓ 明確的 Schema
Return a JSON object with this exact structure:
{
"name": "string (required, 1-100 chars)",
"email": "string (required, valid email format)",
"age": "number (optional, must be 0-150)",
"tags": "array of strings (optional, max 5 items)",
"verified": "boolean (required)",
"joined_date": "ISO 8601 date string (required)"
}
Schema 必須包含:
- 字段名稱(使用一致的命名:snake_case 或 camelCase,不混合)
- 數據類型(string, number, boolean, array, object)
- 必需/可選標記
- 約束條件(長度、範圍、格式)
3. 第二級:提供有效的 JSON 範例
完整的 JSON 輸出範本
Return your answer as valid JSON matching this schema:
Schema:
{
"product_name": "string",
"price_usd": "number",
"in_stock": "boolean",
"reviews": "array of strings",
"last_updated": "ISO date string"
}
Example:
{
"product_name": "Wireless Headphones",
"price_usd": 79.99,
"in_stock": true,
"reviews": ["Great sound", "Comfortable fit", "Good battery"],
"last_updated": "2026-04-11T12:00:00Z"
}
Now, analyze [input] and return your response in the same JSON format.
好的範例有:
- 完整、合法的 JSON(可用 JSON.parse 解析)
- 代表性的數據(顯示所有可能的字段和類型)
- 邊界情況(空陣列、null 值、最小/最大值)
4. 第三級:驗證規則和邊界情況
完整的 JSON 輸出提示詞
Return valid JSON with this schema:
{
"decision": "approved | rejected | pending",
"confidence": "number 0-100",
"reason": "string",
"conditions": "array of strings"
}
Validation rules:
1. "decision" must be one of the three options (enum)
2. "confidence" must be an integer between 0 and 100
3. "reason" must not be empty (min length 5 chars)
4. "conditions" must be an array (can be empty)
5. All four fields must be present (no optional fields)
Example valid response:
{"decision": "approved", "confidence": 95, "reason": "All criteria met", "conditions": []}
Example invalid (don't do this):
{decision: approved, confidence: "95"} ← 缺少引號,字符串值
Critical: Return ONLY valid JSON, no other text.
驗證規則的要點:
- Enum 值:明確列出允許的值
- 數值範圍:指定最小/最大
- 字符串長度:指定 min/max
- 數組限制:最多/最少元素數
- 必需 vs 可選:明確哪些字段必須存在
5. 常見 JSON 陷阱和解決方案
| 陷阱 | 原因 | 解決方案 |
|---|---|---|
| JSON 前有文本 | Claude 習慣性地先說話 | 「Return ONLY valid JSON, no explanation」 |
| Markdown 代碼塊 | Claude 用 ```json ... ``` 包裝 | 「Return raw JSON, not markdown」 |
| 缺少引號 | Claude 用了單引號或無引號 | 範例明確使用雙引號,驗證規則提及 |
| 類型混淆 | Claude 混淆 string vs number | 範例展示每個類型,驗證規則明確 |
| 陣列當物件 | Claude 用 {} 代替 [] | 範例明確展示,說「must be an array」 |
| 多餘欄位 | Claude 添加了未要求的欄位 | 「Return ONLY these fields」+驗證檢查 |
6. 五個實戰案例
案例 1:內容分類系統
Task: Classify a blog article
Schema:
{
"title": "string",
"category": "tech | business | lifestyle | other",
"subcategory": "string",
"confidence": "0-100",
"keywords": "array of 3-5 strings",
"should_recommend": "boolean"
}
Example:
{
"title": "5 AI Prompting Techniques",
"category": "tech",
"subcategory": "artificial intelligence",
"confidence": 95,
"keywords": ["AI", "prompting", "LLM", "techniques"],
"should_recommend": true
}
Important validation:
- category must be one of the 4 values
- confidence must be integer 0-100
- keywords must have 3-5 items
- Return ONLY this JSON, no explanation
案例 2:API 響應聚合
Task: Extract and structure API response data
Schema:
{
"status": "success | error | timeout",
"data": {
"users": "array of {id, name, email}",
"total_count": "number",
"page": "number (1-based)"
},
"error_message": "string or null",
"timestamp": "ISO 8601 date"
}
Example for success:
{
"status": "success",
"data": {
"users": [
{"id": 1, "name": "Alice", "email": "alice@example.com"},
{"id": 2, "name": "Bob", "email": "bob@example.com"}
],
"total_count": 2,
"page": 1
},
"error_message": null,
"timestamp": "2026-04-11T12:00:00Z"
}
Example for error:
{
"status": "error",
"data": null,
"error_message": "Authentication failed",
"timestamp": "2026-04-11T12:00:01Z"
}
案例 3:客戶評分和反饋
Task: Analyze customer feedback
Schema:
{
"overall_sentiment": "very_negative | negative | neutral | positive | very_positive",
"rating_1_5": "1 | 2 | 3 | 4 | 5",
"main_issues": "array of strings (max 3)",
"compliments": "array of strings (max 3)",
"recommendation": "yes | no | maybe",
"actionable_next_steps": "array of strings (1-5 items)"
}
Example:
{
"overall_sentiment": "positive",
"rating_1_5": 4,
"main_issues": ["slow shipping", "packaging could be better"],
"compliments": ["great quality", "friendly customer service"],
"recommendation": "yes",
"actionable_next_steps": [
"Improve shipping speed",
"Redesign packaging for durability",
"Ask for written reviews from 5-star customers"
]
}
案例 4:資料驗證和清理
Task: Validate data quality
Schema:
{
"is_valid": "boolean",
"score": "0-100",
"issues": "array of {field, severity, description}",
"cleaned_data": "object with corrected values or null if invalid"
}
Example for valid data:
{
"is_valid": true,
"score": 95,
"issues": [],
"cleaned_data": {"name": "John Doe", "email": "john@example.com"}
}
Example for invalid data:
{
"is_valid": false,
"score": 40,
"issues": [
{"field": "email", "severity": "critical", "description": "Invalid email format"},
{"field": "age", "severity": "warning", "description": "Age seems unrealistic (500)"}
],
"cleaned_data": null
}
案例 5:決策樹輸出
Task: Decision making with reasoning
Schema:
{
"final_decision": "approved | rejected | needs_review",
"decision_path": "array of strings describing the logic",
"confidence_score": "0-100",
"risks": "array of strings",
"recommendations": "array of strings",
"requires_human_review": "boolean"
}
Example:
{
"final_decision": "approved",
"decision_path": [
"Budget check: $50K available, request is $45K - PASS",
"Timeline check: 3 months available, task needs 2 months - PASS",
"Team capacity: 4 engineers available, need 3 - PASS",
"All criteria met"
],
"confidence_score": 88,
"risks": [
"One engineer is new, may slow down initial progress",
"Tight timeline for Q2 launch"
],
"recommendations": [
"Pair new engineer with experienced one",
"Schedule weekly progress reviews"
],
"requires_human_review": false
}
7. 第四級:Post-Processing 驗證
即使使用了所有最佳實踐,仍應驗證輸出:
Python 驗證範例
import json
from typing import Dict, Any
def validate_json_output(response: str, required_fields: list) -> Dict[str, Any]:
"""
1. Parse JSON
2. Check required fields
3. Validate types
4. Return or raise error
"""
try:
# Remove markdown wrapping if present
if response.startswith("```json"):
response = response[7:-3]
elif response.startswith("```"):
response = response[3:-3]
data = json.loads(response.strip())
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON: {e}")
# Check required fields
for field in required_fields:
if field not in data:
raise ValueError(f"Missing required field: {field}")
return data
驗證清單:
- ✓ JSON 是否能被解析?
- ✓ 所有必需字段是否存在?
- ✓ 字段類型是否正確?
- ✓ 值是否在允許的範圍內?
- ✓ 枚舉值是否在允許的列表中?
8. 常見提示詞模板
通用 JSON 提示詞模板
Your task: [describe what to do]
Return ONLY valid JSON matching this schema:
{
"field_1": "type (required/optional)",
"field_2": "type (constraints)"
}
Validation rules:
- [rule 1]
- [rule 2]
- [rule 3]
Example:
[valid JSON example]
Important:
- Return ONLY JSON, no explanation or markdown
- All required fields must be present
- Follow the exact field names and types
- Do not add extra fields
Now process: [input]
核心要點
- ✅ 明確 schema 是第一步(類型、約束、必需字段)
- ✅ 提供有效的 JSON 範例大幅提升一致性
- ✅ 明確驗證規則:enum、範圍、格式
- ✅ 「Return ONLY JSON」的提示至關重要
- ✅ 後端驗證永遠需要(Claude 不是 100% 可靠)
- ✅ Markdown 包裝常見,需要在後處理中移除