# Claude Code 출력 형식: JSON & 스트림

> **최종 검증**: 2026-10-20 · 📄 공식 문서 기준 (Claude Code CLI 레퍼런스 및 headless 문서, 2026-10-20 확인)

`claude -p --output-format json`은 작업이 끝나면 JSON 객체 하나를 반환하고, `--output-format stream-json`은 실행 중에 줄바꿈으로 구분된 JSON 이벤트를 반환해요. `text`는 플래그를 생략했을 때의 기본값이에요.

스크립트, CI/CD, 자동화 파이프라인에서는 사람이 읽을 수 있는 답변만으로는 부족해요. 프로그램이 파싱할 수 있는 **구조화된 데이터**가 필요하죠. Claude Code의 headless 모드(`claude -p`)는 `--output-format`으로 세 가지 출력 형식을 제공하므로, Claude Code를 여느 CLI 도구처럼 파이프라인에 연결할 수 있어요.

> 이 기능은 Claude Code의 기능이며 **어떤 서비스에 연결하든 무관**해요. Claude Code가 공식 API를 가리키든 QCode를 가리키든 `--output-format`은 동일하게 동작해요. 이 페이지는 출력 형식에 초점을 맞추고, headless 플래그 전체 레퍼런스와 CI 템플릿은 [자동화 & CI/CD](/docs/advanced/headless)에서 확인하세요.

---

## 1. 세 가지 형식 한눈에 보기

| 형식 | 플래그 | 출력 형태 | 사용 사례 |
|------|------|---------|---------|
| 일반 텍스트 | `--output-format text` (기본값) | 일반 텍스트 한 블록 | 사람이 읽기, 단순 파이프 |
| JSON | `--output-format json` | 구조화된 JSON 객체 **하나** | 스크립트 파싱, 비용/사용량/세션 ID 읽기 |
| 스트리밍 JSON | `--output-format stream-json` | **줄바꿈으로 구분된** JSON 이벤트 스트림 | 실시간 진행 상황, 단계별 소비, 긴 작업 |

```bash
# text is the default, so these two lines are equivalent
claude -p "Explain idempotence in one sentence"
claude -p "Explain idempotence in one sentence" --output-format text
```

---

## 2. text: 기본 일반 텍스트

`--output-format`을 지정하지 않으면 `text`가 적용돼요. stdout은 그대로 모델의 최종 답변이므로 직접 읽거나 단순 파이프에 넘기기 좋아요.

```bash
# Read directly
claude -p "Rewrite this function to be async"

# Pipe to another tool
claude -p "Generate 5 candidate commit messages" | head -5

# Write to a file
claude -p "Write a short README intro for this repo" > intro.txt
```

**한계**: text는 "답변"만 줘요. 비용, 토큰 사용량, 세션 ID 같은 메타데이터가 없고, 여러 단계로 진행된 작업과 최종 결과를 구분할 수 없어요. 그런 정보가 필요하면 `json`이나 `stream-json`으로 바꾸세요.

---

## 3. json: 구조화된 객체 하나

`--output-format json`은 작업이 **완료된 뒤** JSON 객체 **하나**를 출력하며, 최종 결과와 여러 메타데이터 필드를 담고 있어요. 스크립트에서 가장 많이 쓰는 형식이에요.

```bash
claude -p "Count how many TODO comments are under src/" --output-format json
```

반환되는 객체의 주요 필드는 다음과 같아요 (실제 필드는 버전에 따라 달라요):

| 필드 | 의미 |
|------|------|
| `result` | 최종 답변 텍스트 |
| `total_cost_usd` | 이번 호출의 비용 (USD) |
| `usage` | 토큰 사용량 (입력 / 출력 / 캐시 등) |
| `session_id` | 세션 ID, `--resume`으로 이어서 사용 가능 |

### jq로 파싱하기

`json` 형식은 [`jq`](https://jqlang.org/)와 잘 맞아요:

```bash
# Just the final answer
claude -p "Summarize this change in one sentence" --output-format json | jq -r '.result'

# Pull out the cost of this call
claude -p "Review auth.py" --output-format json | jq '.total_cost_usd'

# Grab several fields at once
claude -p "Analyze the architecture" --output-format json \
  | jq '{cost: .total_cost_usd, session: .session_id, tokens: .usage}'
```

### 스크립트에서 분기하고 비용 누적하기

```bash
#!/usr/bin/env bash
set -euo pipefail

out=$(claude -p "Write unit tests for UserService" \
        --output-format json --max-turns 8)

result=$(echo "$out" | jq -r '.result')
cost=$(echo "$out"   | jq -r '.total_cost_usd')
sid=$(echo "$out"    | jq -r '.session_id')

echo "Result: $result"
echo "Cost this call: \$$cost"
echo "Session ID: $sid (resume with claude --resume $sid)"
```

### --json-schema로 구조화된 출력 받기

`--output-format json`에 `--json-schema`와 JSON Schema 정의를 추가하면, 응답의 `structured_output` 필드에 구조화된 결과가 담기고 요청에 대한 메타데이터(세션 ID, 사용량 등)도 함께 와요. 아래 예시는 함수 이름을 문자열 배열로 추출하고 jq로 구조화된 부분만 남겨요:

```bash
claude -p "Extract function names from auth.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
  | jq '.structured_output'
```

`| jq '.structured_output'` 부분을 빼면 응답 전체가 출력돼요. 값이 유효한 JSON Schema가 아니면 `claude`는 `Error: --json-schema is not a valid JSON Schema`와 함께 검증기의 진단 메시지를 출력하고 종료해요.

> **팁**: `json`은 작업이 끝난 뒤 객체 전체를 한 번에 출력하므로, 긴 작업이 실행되는 동안에는 아무 출력도 없어요. 진행 상황을 실시간으로 보려면 아래의 `stream-json`을 사용하세요.

---

## 4. stream-json: 실시간 이벤트 스트림

`--output-format stream-json`은 실행을 **줄바꿈으로 구분된 JSON 이벤트**(NDJSON)로 나누어 한 줄에 이벤트 하나씩 즉시 출력해요. 긴 작업의 실시간 진행 상황, 스트리밍 UI, 출력이 생성되는 대로 소비하는 파이프라인에 적합해요.

```bash
claude -p "Refactor the whole utils directory and add tests" \
  --output-format stream-json --max-turns 20
```

출력은 다음과 같은 모습이에요 (각 줄은 독립적인 JSON이며, 필드는 버전에 따라 달라요):

```
{"type":"system","subtype":"init","session_id":"..."}
{"type":"assistant","message":{...}}
{"type":"assistant","message":{...}}
{"type":"result","result":"...","total_cost_usd":0.0123,"usage":{...}}
```

### 한 줄씩 소비하기

모든 줄이 유효한 JSON이므로 스트리밍되는 대로 처리할 수 있어요:

```bash
# Print the type of each event in real time
claude -p "Migrate to the new API" --output-format stream-json \
  | jq -r '.type'

# Pull result and cost only when the final event appears
claude -p "Migrate to the new API" --output-format stream-json \
  | jq -r 'select(.type == "result") | "\(.result)\nCost $\(.total_cost_usd)"'
```

```bash
# Process line by line with a while loop for live progress feedback
claude -p "Repository-wide code review" --output-format stream-json | \
while IFS= read -r line; do
  type=$(echo "$line" | jq -r '.type')
  case "$type" in
    system) echo "▶ Starting…" ;;
    assistant) echo "… thinking" ;;
    result) echo "✓ Done: $(echo "$line" | jq -r '.result')" ;;
  esac
done
```

### 토큰 단위 및 서브에이전트 이벤트

- `--include-partial-messages`: `--output-format stream-json --verbose`와 함께 사용하면 생성되는 대로 토큰을 받아요. 각 줄은 이벤트를 나타내는 JSON 객체예요.
- `--include-hook-events`: 훅 생명주기 이벤트를 출력 스트림에 포함해요 (`--output-format stream-json` 필요).
- `--forward-subagent-text`: 서브에이전트 텍스트를 stream-json 출력 스트림으로 내보내요 (`--print`와 `--output-format stream-json` 필요, Claude Code v2.1.211 이상). 이 옵션이 없으면 포그라운드 서브에이전트의 텍스트는 생략돼요.
- `--input-format stream-json`: print 모드에서 입력을 텍스트 프롬프트 대신 JSON 스트림으로 받아요.

> **`json` vs `stream-json`**: `json`은 작업이 끝날 때까지 기다렸다가 완전한 객체 **하나**를 주므로 파싱이 간단해요. `stream-json`은 실행 내내 **여러** 이벤트를 스트리밍하므로 실시간 피드백이 가능하지만 한 줄씩 파싱해야 해요. CI에서는 최종 결과에는 `json`을, 진행 로그에는 `stream-json`을 사용하세요.

---

## 5. CI / 파이프라인 레시피

### GitHub Actions에서 결과를 받아 코멘트 남기기

```yaml
- name: Claude review
  env:
    ANTHROPIC_BASE_URL: https://api.qcode.cc/api
    ANTHROPIC_AUTH_TOKEN: ${{ secrets.QCODE_API_KEY }}
  run: |
    out=$(claude -p "Review this PR's diff and list issues" \
            --output-format json --max-turns 6 --allowedTools Read,Glob,Grep)
    echo "$out" | jq -r '.result' > review.md
    echo "This review cost \$$(echo "$out" | jq -r '.total_cost_usd')"
```

### 비용 게이트 추가하기 (예산 초과 시 실패)

```bash
out=$(claude -p "Generate release notes" --output-format json)
cost=$(echo "$out" | jq -r '.total_cost_usd')
# Float comparison with awk: fail CI if over $0.50
awk -v c="$cost" 'BEGIN{ exit (c > 0.5) ? 1 : 0 }' \
  || { echo "Cost \$$cost over budget"; exit 1; }
echo "$out" | jq -r '.result'
```

### 여러 호출에 걸쳐 비용 누적하기

```bash
total=0
for f in src/*.py; do
  out=$(claude -p "Write docstrings for $f" --output-format json)
  c=$(echo "$out" | jq -r '.total_cost_usd')
  total=$(awk -v t="$total" -v c="$c" 'BEGIN{ printf "%.4f", t + c }')
done
echo "Total cost across all files: \$$total"
```

> **QCode 가리키기**: 위 명령은 공식 API와 QCode에서 동일해요. `ANTHROPIC_BASE_URL`을 `https://api.qcode.cc/api`로 지정하고(주의: **끝에 슬래시 없음**) `cr_` 키를 `ANTHROPIC_AUTH_TOKEN`에 넣으면 돼요. 중국 사용자는 `asia.qcode.cc`를 사용할 수 있어요. [엔드포인트 & API 형식](/docs/getting-started/endpoints-and-api-paths)을 참고하세요.

---

## 6. 흔한 실수

- **`json`은 긴 작업 중에 조용해요**: 끝날 때 한 번만 출력하므로 진행 상황이 안 보이는 게 정상이에요. 진행 상황이 필요하면 `stream-json`을 사용하세요.
- **`stream-json`을 하나의 덩어리로 `jq`할 수 없어요**: NDJSON이므로 여러 객체가 하나의 JSON 문서를 이루지 않아요. 한 줄씩 `jq`, `jq -c`, `--stream`을 사용하고, 스트림 전체에 `jq '.'`를 실행하지 마세요.
- **`--max-turns`를 잊지 마세요**: 자동화에서는 턴 수를 제한해 작업이 통제를 벗어나 비용을 태우지 않도록 하세요.
- **BASE_URL에 끝 슬래시를 붙이지 마세요**: `https://api.qcode.cc/api`가 맞아요. `/`를 하나 더 붙이면 잘못된 경로가 만들어져요.
- **메타데이터 필드는 버전에 따라 달라요**: 내 컴퓨터에서 `claude -p ... --output-format json`의 실제 출력을 믿으세요. 먼저 `jq 'keys'`를 실행해 어떤 필드가 있는지 확인하세요.

---

## 다음 단계

- [자동화 & CI/CD](/docs/advanced/headless) — headless 플래그 전체 레퍼런스와 CI/CD 레시피
- [서브에이전트](/docs/advanced/subagents) — Claude Code가 백그라운드 에이전트를 병렬로 조율하도록 하기
- [비용 최적화](/docs/usage/cost-optimization) — `total_cost_usd`로 비용 관리하기
- [엔드포인트 & API 형식](/docs/getting-started/endpoints-and-api-paths) — 세 가지 도메인과 프로토콜 경로

> Claude Code를 파이프라인에 연결하면 비용은 출력에 그대로 나와요. [QCode 플랜 & 요금 보기](https://qcode.cc/pricing)에서 자동화 규모에 맞는 등급을 선택하세요.