教程

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 API 流式输出完全指南:Server-Sent Events 实时响应实战Claude API 流式输出(Streaming)完整教程:为什么用流式输出(用户体验提升50%+)、Server-Sent Events 协议原理、Python/Node.js/curl 三种实现方式、stream=True 的事件类型(message_start/content_block_delta/message_stop)、流式 Tool Use 的特殊处理、在 FastAPI/Express/Next.js 中实现流式 API 端点,以及流式输出的错误处理和超时配置。2026/3/20教程Claude Code MCP 完整使用指南:安装配置主流 MCP 服务器扩展 AI 能力Claude Code MCP(Model Context Protocol)完整使用指南:MCP 是什么(AI 工具扩展标准)、claude mcp 命令管理服务器(add/remove/list)、主流 MCP 服务器安装配置(文件系统/GitHub/PostgreSQL/Brave Search/Slack)、本地 stdio 与远程 SSE 两种连接方式、MCP 服务器安全配置、在 CLAUDE.md 中声明 MCP 工具使用规范,以及自定义 MCP 服务器的快速开发入门。2026/3/18教程Claude Code 项目初始化最佳实践:新项目 5 分钟搭建完美 AI 编程环境Claude Code 新项目最佳初始化流程:CLAUDE.md 标准模板(项目背景/技术栈/代码规范/禁止操作)、.claudeignore 初始配置、.claude/commands/ 常用命令预置、settings.json 权限与模型设置、--init 命令的自动化初始化、项目级 vs 全局配置的优先级说明,以及不同类型项目(Web前端/后端API/全栈/开源库)的专项初始化模板。2026/3/18教程Claude Code 权限管理完全指南:精确控制 AI 能执行哪些操作Claude Code 权限系统完整解析:四种权限模式(default/acceptEdits/bypassPermissions/plan)、--allowedTools 和 --disallowedTools 精确工具控制、Bash 命令白名单语法(通配符匹配)、settings.json 持久化权限配置、CLAUDE.md 中的权限规则声明、CI/CD 自动化场景的权限配置、以及如何在效率和安全之间找到平衡点。2026/3/18教程Claude Code 自定义斜杠命令完全指南:用 /命令 封装常用工作流Claude Code 自定义斜杠命令(slash commands)完整教程:命令文件创建位置(.claude/commands/)、Markdown 格式规范、$ARGUMENTS 参数传递、项目级命令 vs 用户全局命令的区别、实用命令示例(/review、/test、/deploy-check、/refactor、/standup)、命令组合调用,以及如何在团队中共享和版本管理自定义命令。2026/3/18教程Claude Code .claudeignore 完全指南:精准控制 AI 读取文件的范围Claude Code .claudeignore 文件完整使用指南:语法规则(与 .gitignore 完全一致)、为什么需要排除文件(隐私/性能/干扰)、推荐排除的文件类型(node_modules/secrets/.env/构建产物)、按项目类型的最佳实践配置(Node.js/Python/Go/单体仓库)、.claudeignore 与 .gitignore 的区别,以及如何验证排除规则是否生效。2026/3/18