GrepBoard/Manuals
605 manuals ·

Get claude -p output as JSON and use it in a script

·Tested on Claude Code 2.1.302 · Linux · jq · model Claude Opus 5.5 · 2026-10·Test scope ↓·7 steps

Switch claude -p to --output-format json, pull result out with jq, and branch on the exit code and is_error so a shell script can tell success from failure.

claude -p "prompt" prints the answer without opening a chat screen and exits. To feed that into a pipe or a variable, pick the output format first.

[1] The default output is plain text. The answer goes to stdout as one block.

console
$ claude -p "Reply with the single word: pong"pong$ echo $?0

A successful run exits 0; a run that fails exits non-zero.

[2] Add --output-format json to get a single JSON object. The fields below were pulled with jq from the real output of the same prompt.

console
$ claude -p "Reply with the single word: pong" --output-format json > out.json$ jq -c '{type,subtype,is_error,result,num_turns,total_cost_usd,stop_reason,terminal_reason}' out.json{"type":"result","subtype":"success","is_error":false,"result":"pong","num_turns":1,"total_cost_usd":0.0041066,"stop_reason":"end_turn","terminal_reason":"completed"}

The object had 26 top-level keys in all, among them usage, modelUsage, duration_ms, permission_denials and uuid. They can change between versions, so read only the keys you need.

KeyValue
resultThe answer text (string)
is_errorWhether the run failed. false on success
total_cost_usdEstimated cost of the run. Differs on every run
session_idSession ID. Pass it to --resume to continue
num_turnsAgent turns taken

[3] To get only the answer, extract result with jq -r .result. -r strips the quotes.

console
$ jq -r .result out.jsonpong$ answer=$(claude -p "Reply with the single word: pong" --output-format json | jq -r .result)

[4] For line-by-line progress, use stream-json. With -p it requires --verbose; without it the run ends like this:

console
$ claude -p "Reply with the single word: pong" --output-format stream-jsonError: When using --print, --output-format=stream-json requires --verbose

With --verbose, each line is one JSON object. This prompt produced three lines (session_id is cut to its first 8 characters).

console
$ claude -p "Reply with the single word: pong" --output-format stream-json --verbose > out.jsonl$ jq -c '{type,subtype,session_id:(.session_id[0:8])}' out.jsonl{"type":"system","subtype":"init","session_id":"4df3dcf5"}{"type":"assistant","subtype":null,"session_id":"4df3dcf5"}{"type":"result","subtype":"success","session_id":"4df3dcf5"}

The last line is the result message. The final answer, cost and session info are there.

[5] In a script, check both the exit code and is_error. The docs say a failure inside the run, such as missing authentication, is printed as the result on stdout, so the exit code alone can miss it.

bash
#!/usr/bin/env bash# usage: ask.sh "prompt"out=$(claude -p "$1" --output-format json --max-turns 3 --allowedTools "Read")rc=$?if [ "$rc" -ne 0 ]; then  echo "claude exited with $rc" >&2  exit "$rc"fiif [ "$(jq -r .is_error <<<"$out")" != "false" ]; then  echo "claude reported an error: $(jq -r .result <<<"$out")" >&2  exit 1fijq -r .result <<<"$out"

The branches were checked with a stand-in command in place of claude. The real JSON above gave pong and 0, a JSON with is_error set to true gave the error text and 1, and a stand-in that exited 3 gave claude exited with 3 and 3.

[6] Limit the scope. --max-turns caps the number of agent turns and the run exits with an error when the cap is hit (no limit by default). --allowedTools lists the tools that run without a prompt. Narrow commands with a prefix rule:

console
$ claude -p "Look at my staged changes and create an appropriate commit" \    --max-turns 5 \    --allowedTools "Bash(git diff *)" "Bash(git log *)" "Bash(git status *)" "Bash(git commit *)"

The space before the * matters: without it, Bash(git diff*) also matches git diff-index. To remove tools altogether, use --tools or --disallowedTools. To block commands with a hook, see Block dangerous commands with a Claude Code hook.

[7] Put a ceiling on repeated calls. --max-budget-usd 1.00 stops the run once estimated spend reaches that amount; the docs say spend can pass the cap, so leave headroom. Every claude -p call costs tokens, so a loop multiplies the bill.

Check it with the JSON · YAML formatter and converter tool ↗ — calculated in your browser.

#claude-code#headless#json