教程

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

相关文章推荐

教程Claude Code Skills 进阶:动态上下文注入、路径限定激活和 Subagent 集成深度指南Claude Code Skills 三个高级特性深度指南:动态上下文注入(!! 命令预处理原理、内联和多行语法、实战健康检查 Skill 含 6 个命令块、安全注意事项);路径限定自动激活(TypeScript 严格模式/SQL 安全/React 组件三个实战示例);context: fork 在 Subagent 运行(适用场景判断、agent 类型选择);以及三种特性组合的完整 PR 审查 Skill 示例。2026/5/10教程Claude Code Skills 官方完整指南:从入门到高级模式的权威教程Claude Code Skills 官方文档完整中文整理:Skills vs CLAUDE.md 核心区别;目录结构;存储位置和优先级;实时变更检测和 Monorepo 自动发现;完整 Frontmatter 字段参考(20+字段);字符串替换(动态参数);内容类型(参考类 vs 任务类);调用控制表;Skill 内容生命周期(压缩保留机制);三个高级模式(动态注入/路径限定/Subagent运行);以及内置 Bundled Skills 和权限控制方法。2026/5/10教程Claude Code Slack 集成完整指南:团队协作、CI 通知和权限管理Claude Code Slack 集成完整指南:5 大核心功能(频道触发任务/代码问答/CI 通知/PR 审查/Routines 结果推送);安装配置步骤;4 个权限等级(read/write/execute/pr)及频道级配置;人工审批工作流;GitHub Actions + Slack 通知自动化;4 个团队协作场景(新人上手/PM 提需求/频道分工规范/结构化请求模板);以及官方 Slack 集成 vs OpenClaw 方案的对比。2026/5/8教程Claude Code 定时任务完整指南:/schedule、Routines 三种触发方式和 /loop 监控/schedule 命令和 Routines 完整指南:/schedule 创建/查看/运行/编辑/删除定时任务;Routines 三种触发方式(Cron 定时/GitHub 事件/Webhook API /fire 端点);4 个实战 Routine 配置(每日健康检查/PR 自动质量门/每周技术债扫描/CI 失败分析);/loop 会话内定期重复(vs /schedule 的区别对比);Routines 访问权限配置(GitHub/Slack/数据库);以及 Routines + ultrareview/Hooks/Subagents 的组合用法。2026/5/8教程Claude Code Sub-agents 官方完整指南:内置 Agent、自定义配置、并行模式和 Fork 会话Claude Code Sub-agents 官方文档完整整理:解决的核心问题(保护上下文/成本控制);三个内置 Sub-agent(Explore/Plan/General-purpose 及各自模型和工具);/agents 创建流程(界面/描述生成/工具选择/持久内存配置);完整 Frontmatter 字段参考;模型选择策略(Haiku 探索→Sonnet 审查→Opus 复杂任务);MCP 服务器限定到 Sub-agent;自动委托 vs 显式调用;前台/后台运行;隔离高容量/并行调研/链式 Sub-agent 三种模式;Fork 会话(与命名 Sub-agent 的区别);以及 4 个官方示例配置。2026/5/8教程Claude Code 官方最佳实践完全指南:Anthropic 工程团队总结的 25 条黄金法则Anthropic 官方 Best Practices 完整整理:核心约束(上下文管理);给 Claude 可验证标准(最高杠杆);探索→规划→实现→提交四步流程;精准提示 4 策略;丰富上下文输入方式;CLAUDE.md 有效写法(含 ✅/❌ 清单和 @ 引入语法);权限预设;CLI 工具配置;MCP 服务器选择;Hooks 自动化;Skills vs CLAUDE.md 选择;高效沟通技巧;会话管理(提前纠正/激进 /compact/Subagent 调研);以及非交互模式和多 Session 并行的规模化技巧。2026/5/8