In `claude -p`, when do you choose `--output-format json`, `stream-json` or `--json-schema`, and what does a script read from each?
answer
- one object versus many lines
- result, session_id, total_cost_usd
- schema data lands in its own field
- system/init first, result last
- costs are client-side estimates
basics
~10 sUse json for one final object a script parses (result, session_id, total_cost_usd), stream-json for newline-delimited events while the run progresses, and --json-schema with json output when you need validated data in structured_output.
solid answer
~40 s`--output-format json` prints one object when the run ends: the text in `result`, plus `session_id`, usage and `total_cost_usd` with a per-model breakdown, which `jq -r '.result'` reads. `stream-json` prints newline-delimited JSON events as they happen; the docs pair it with `--verbose`, `--include-partial-messages` adds token deltas, a `system/init` event reports the model, tools, MCP servers and plugins, and the last line is the `result` message. For data a program consumes, add `--json-schema '<schema>'` to `--output-format json`: the validated object arrives in `structured_output`. An invalid schema makes `claude` exit with an error, and the `format` keyword is treated as an annotation, not enforced. Cost figures are client-side estimates, not the bill.
code
bash · 6 linesout=$(claude -p "Read lint.log and group the failures into safe autofixes and manual fixes" \
--output-format json \
--json-schema '{"type":"object","properties":{"safe":{"type":"array","items":{"type":"string"}},"manual":{"type":"array","items":{"type":"string"}}},"required":["safe","manual"]}')
echo "$out" | jq '.structured_output.manual'
echo "$out" | jq -r '.session_id' > last-session.txt
echo "$out" | jq '.total_cost_usd'go deeper
Recall the three values of --output-format, that text is the default, and that json puts the answer in result and the conversation ID in session_id.
Explain json against stream-json, what system/init and the final result message carry, and how --json-schema returns validated data in structured_output.
Show how a pipeline fails fast on mcp_server_errors or plugin_errors, logs total_cost_usd as an estimate, and validates format-keyword fields itself.
Weigh parsing claude -p output in scripts against moving to the Agent SDK's typed messages once several services depend on the same structured results.
## Why the format matters `claude -p` runs Claude Code without a terminal interface and prints the outcome to stdout. The `--output-format` flag decides what that outcome looks like, and therefore how much work the calling script has to do. The default, `text`, is the final response as prose: fine for a human or a file, useless for a script that needs a session ID, a cost figure or a list it can loop over. | Choice | Shape on stdout | What a script reads | | --- | --- | --- | | `text` (default) | Plain text of the final response | The whole stdout | | `json` | One JSON object at the end | `result`, `session_id`, `total_cost_usd`, usage | | `stream-json` | One JSON event per line, as the run goes | Event `type`s, ending with a `result` message | | `json` + `--json-schema` | One object; your data validated | `structured_output` | ## `--output-format json`: one object at the end With `json`, nothing is printed until the run finishes; then a single object arrives. The fields scripts use most: - **`result`** holds the final response text: `claude -p "Summarize this project" --output-format json | jq -r '.result'`. - **`session_id`** identifies the conversation, so a later call can continue it with `--resume`. - **`total_cost_usd`** and a **per-model cost breakdown** let a script log or alert on spend without opening a dashboard. When the call continued an earlier conversation, the figure is the conversation's whole total, earlier runs included. The cost fields are **client-side estimates** computed from a bundled price table. They are good for trend lines and caps, and can still differ from the invoice. ## `--output-format stream-json`: events as they happen `stream-json` prints **newline-delimited JSON**: every line is a complete event. Use it when something must react while the run is still going, such as a dashboard, a log shipper or a wrapper that shows progress. The docs pair it with `--verbose`, and: 1. A **`system/init`** event reports session metadata: model, tools, MCP servers and loaded plugins. It is first unless startup events, such as plugin installs or `SessionStart` hook output, come before it. Its `plugin_errors` and `mcp_server_errors` fields let CI fail fast when something did not load. 2. **Assistant and user messages** follow as Claude works; messages from subagents carry a `parent_tool_use_id`, while the main conversation's carry `null`. 3. **`system/api_retry`** events announce retries after retryable API errors. 4. With **`--include-partial-messages`**, `stream_event` lines carry token deltas, so text can be shown as it is generated. 5. The **last line is a `result` message** with the final text, the cost and session metadata; when tool calls were denied, its `permission_denials` lists them. ## `--json-schema`: validated structured output When a program, not a person, consumes the answer, prose is a liability. Pass `--output-format json` together with `--json-schema` and a JSON Schema definition. Claude does the task with whatever tools it needs and returns data that matches the schema; the object appears in the **`structured_output`** field, next to the usual metadata. Two behaviours to know: - If the value is not a valid JSON Schema, `claude` **exits with an error** (`Error: --json-schema is not a valid JSON Schema`) and the validator's diagnostic, rather than answering in free text. - The **`format` keyword** (for example `"format": "email"`) is accepted but treated as an annotation, so it is **not enforced**. Validate such fields yourself if they matter. `--json-schema` is print-mode only. The Agent SDK has its own structured-output option for code that embeds the loop as a library. ## Picking one for a nightly job - A job that writes a report a person reads: `text`, redirected to a file, guarded by the exit status. - A job that triages failures and files tickets: `json` with `--json-schema`, read from `structured_output`. - A job whose progress you watch, or whose denied calls and load errors you want to see as they occur: `stream-json`, parsed line by line. Whatever you pick, read `session_id` if a later step may continue the conversation, and log `total_cost_usd` so spend drift shows up before the bill does. ## Common parsing mistakes - **Reading `result` without checking the outcome.** A run that failed or hit a cap still produces a result object; check the exit status before treating `result` or `structured_output` as the answer. - **Treating `stream-json` as one document.** Each line is its own JSON object, so parse line by line instead of handing the whole stream to a single JSON parser. - **Summing costs across resumed calls.** A continued conversation already reports its running total, so adding the figures double-counts.
- Why is `system/init` useful as a CI gate in `stream-json` output?It lists the MCP servers and plugins the session actually loaded. A `--mcp-config` entry that fails validation is skipped and the run still exits cleanly, so a CI step should fail when `mcp_server_errors` or `plugin_errors` is non-empty instead of trusting the exit status.
- Why can't you treat `total_cost_usd` as the billed amount?It is a client-side estimate computed from a price table bundled with Claude Code, so it can drift from what you are billed. Use it for logging, alerting and caps, and reconcile against the provider's billing for the real figure.
- json output streams events while the run is still going
- total_cost_usd is the exact amount that will appear on the bill
- The format keyword in a --json-schema schema is enforced on the output
- An invalid --json-schema just falls back to free text in result
- system/init is always the very first line of stream-json output