教程

Claude Code 输出格式控制完全指南:JSON、流式、结构化输出使用方法

Claude Code 和 Claude API 输出格式完整控制指南:--output-format 参数(text/json/stream-json)、非交互模式(-p)的输出控制、结构化 JSON 输出(--json-schema 字段约束)、流式输出(Server-Sent Events)的处理方式、include-partial-messages 流式渐进显示、以及 CI/CD 管道中解析 JSON 输出的实用技巧。

2026/3/183分钟 阅读ClaudeEagle

在非交互模式(-p 或 --print)下,Claude Code 支持多种输出格式, 满足脚本集成、CI/CD 管道和实时显示的不同需求。

三种输出格式

通过 --output-format 参数指定:

格式参数值适合场景
纯文本text(默认)人类阅读、简单脚本
JSON 对象json程序解析、CI/CD
流式 JSONstream-json实时显示、长任务

text 格式(默认)

bash
# 最简单,直接输出 Claude 的文字回复
claude -p "列出 Python 列表去重的 3 种方法"

# 输出:
# 1. 使用 set():list(set(lst))
# 2. 使用 dict.fromkeys():list(dict.fromkeys(lst))
# 3. 使用列表推导:[x for i, x in enumerate(lst) if x not in lst[:i]]

json 格式(程序集成推荐)

bash
claude -p "分析这段代码有什么问题" --output-format json

输出示例:

json
{
  "type": "result",
  "subtype": "success",
  "session_id": "session_abc123",
  "cost_usd": 0.00234,
  "duration_ms": 2341,
  "num_turns": 1,
  "result": "分析结果:该代码存在以下问题...",
  "is_error": false
}

在脚本中解析:

bash
# 提取 result 字段
RESULT=$(claude -p "分析代码" --output-format json | python3 -c "
import json, sys
data = json.load(sys.stdin)
print(data['result'])
")
echo "$RESULT"
python
import subprocess, json

output = subprocess.run(
    ["claude", "-p", "分析这段代码", "--output-format", "json"],
    capture_output=True, text=True
)
data = json.loads(output.stdout)
print(data["result"])
print(f"耗时:{data['duration_ms']}ms,成本:${data['cost_usd']:.4f}")

stream-json 格式(实时流式)

适合长任务,边生成边处理:

bash
claude -p "写一篇 2000 字的技术文章"   --output-format stream-json   --include-partial-messages

流式事件示例:

json
{"type": "system", "subtype": "init", "session_id": "xxx", ...}
{"type": "assistant", "message": {"role": "assistant", "content": [{"type": "text", "text": "# 文章标题

第一段..."}]}, "turn_number": 1}
{"type": "result", "subtype": "success", "cost_usd": 0.05, ...}

Python 处理流式输出:

python
import subprocess, json

process = subprocess.Popen(
    ["claude", "-p", "写一篇长文", "--output-format", "stream-json",
     "--include-partial-messages"],
    stdout=subprocess.PIPE, text=True
)

for line in process.stdout:
    line = line.strip()
    if not line:
        continue
    event = json.loads(line)
    if event["type"] == "assistant":
        # 实时打印流式内容
        for block in event["message"]["content"]:
            if block["type"] == "text":
                print(block["text"], end="", flush=True)
    elif event["type"] == "result":
        print(f"

成本:${event['cost_usd']:.4f}")

结构化 JSON 输出(--json-schema)

让 Claude 严格按照指定 Schema 输出:

bash
claude -p "分析这段 Python 代码的问题"   --output-format json   --json-schema '{
    "type": "object",
    "properties": {
      "issues": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "severity": {"type": "string", "enum": ["critical", "major", "minor"]},
            "line": {"type": "integer"},
            "description": {"type": "string"},
            "suggestion": {"type": "string"}
          }
        }
      },
      "overall_score": {"type": "integer", "minimum": 0, "maximum": 100}
    }
  }'

输出将严格符合 Schema:

json
{
  "issues": [
    {
      "severity": "major",
      "line": 15,
      "description": "未处理异常可能导致程序崩溃",
      "suggestion": "添加 try-except 块"
    }
  ],
  "overall_score": 72
}

CI/CD 管道集成示例

yaml
# .github/workflows/code-review.yml
- name: AI Code Review
  run: |
    REVIEW=$(claude -p "对以下改动做代码审查,输出 JSON"       --output-format json       --json-schema '{"type":"object","properties":{"approved":{"type":"boolean"},"issues":{"type":"array","items":{"type":"string"}}}}'       < git_diff.txt)

    APPROVED=$(echo "$REVIEW" | python3 -c "import json,sys; print(json.load(sys.stdin)['result'])" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('approved','false'))")

    if [ "$APPROVED" = "false" ]; then
      echo "AI 审查未通过"
      exit 1
    fi

input-format:接收流式 JSON 输入

配合其他工具的流式输出:

bash
# 接收流式 JSON 输入,输出 JSON
some-tool --output stream-json |   claude -p "总结以上内容"     --input-format stream-json     --output-format json

来源:Claude Code 官方文档 - docs.anthropic.com/en/docs/claude-code/cli-reference

相关文章推荐

教程MCP Server 2026 实战教程:五个值得优先安装的 Server 完整配置指南MCP Server 2026完整配置教程:详解Filesystem/Memory/GitHub/Playwright/Fetch五个值得优先安装的Server,附全局与项目级配置组织方式、验证与故障排查思路、远端MCP Server新特性(SSE)、安全考量清单,是Claude Code扩展工具能力的实战起点。2026/8/25教程Claude Code Hooks 6 大生产级实战场景:从一次 rm -rf 事故说起Claude Code Hooks完整实战指南:从rm -rf误删配置文件真实事故切入,详解PreToolUse/PostToolUse等6大生命周期事件,附危险命令拦截、敏感文件保护、自动Lint、上下文注入、异步审计、HTTP合规对接完整脚本,含退出码等关键踩坑点。2026/8/25教程Claude Code Week 34:/design 技能上线,可编辑 UI 画板、Concise 输出风格、手机一键启动会话Claude Code 2026年8月17-21日(Week 34)更新详解:全新/design技能带来可编辑UI画板工作流(研究预览)、Concise内置输出风格直给结果跳过过程叙述、Remote Control正式版支持手机一键启动本机会话,附完整使用方法与实战建议。2026/8/23教程Claude Code v2.1.239:修复 Bedrock 代理下静默双倍计费漏洞,/claude-api upgrade 一键迁移 SDK详解Claude Code v2.1.239更新:修复Bedrock流式传输代理剥离Content-Type头导致静默双倍计费的重要问题、数据驻留工作区成本估算加入1.1倍溢价、新增/claude-api upgrade一键迁移Python SDK到1.x、云端插件同步区分来源、Alpine musl原生插件加载修复。2026/8/22教程Claude Code v2.1.238:Remote Control 连接韧性大幅提升,新增 readline 风格快捷键详解Claude Code v2.1.238更新:新增keybindingFlavor readline快捷键风格、插件市场headersHelper动态认证头、自托管Runner缓冲关闭与代理认证增强、Remote Control网络断连/登录过期/进程崩溃后自动恢复等一揽子稳定性修复、长会话内存无限增长问题修复。2026/8/21教程CLAUDE.md、Rules、Skills、Subagents、Hooks 到底该用哪个?Anthropic 官方给出决策指南Anthropic官方决策指南详解Claude Code五种指令控制机制:Path-scoped Rules按路径精准加载省Token、Skills程序性操作手册动态加载、Subagents隔离上下文支持五层嵌套、Hooks确定性拦截控制、Output styles高权重系统提示注入,附完整决策速查表。2026/8/20