brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: --json-schema makes claude -p return JSON you can trust

Claude
~/tips/tip-claude-json-schema-output

claude -p "Extract the main function names from auth.py" \

Makes a scripted Claude Code run return validated JSON instead of free text.

Parsing free text from a script is how you get a Tuesday-night bug. If you use claude -p in a script, ask for a schema.

Combine --output-format json with --json-schema and the response carries your data in a structured_output field, next to metadata such as the session ID and usage.

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

That prints an object with a functions array of strings. The plain text answer without a schema sits in .result, so jq -r '.result' gets you that instead.

I would reach for this the moment a script has to do something with the answer: build a list or decide yes or no. Describe the shape once, and the next step in your pipeline can rely on it, which is much calmer than a regex over prose.

Two caveats. If a run ends without valid output, for example because Claude declined the request, the structured_output field is missing, so check for it before your script uses it. And the format keyword, like "format": "email", is accepted but treated as an annotation and not enforced.

Further reading: Run Claude Code programmatically – Claude Code docs, CLI reference – Claude Code docs, On this site: cap a headless Claude run with –max-turns and –max-budget-usd, On this site: scope –allowedTools to single git commands, with a space before the star

More Claude tips /recap /focus /skill-doctor /autocompact 500k claude purge ~/work/my-repo --dry-run All Claude tips (83) All topics

Link