Reliable Structured JSON Output Pattern
Get valid, schema-conforming JSON from any model using native structured outputs where available, and validate-and-repair otherwise.
Order of preference
- Native structured outputs (e.g. OpenAI
response_format: {type: "json_schema", ...}withstrict: true, or tool calling with a schema). - JSON mode plus schema in the prompt.
- Prompt-only plus validation and a repair retry.
Prompt (fallback path)
Extract the fields below from the text. Return ONLY a JSON object matching this schema,
with no markdown fences or commentary. Use null for unknown values; do not guess.
Schema: {"name": string, "email": string|null, "company": string|null}
Text: """{{input}}"""Validate and repair
import json, jsonschema
def get_json(call, prompt, schema, retries=2):
msg = prompt
for _ in range(retries + 1):
raw = call(msg)
try:
data = json.loads(raw)
jsonschema.validate(data, schema)
return data
except Exception as e:
msg = f"{prompt}\n\nYour previous output was invalid: {e}. Return corrected JSON only."
raise ValueError("Could not obtain valid JSON")Failure modes
- Schema-valid output can still be semantically wrong; add business-rule checks.
- Repair loops without a limit; cap retries.
- Providers support different schema features; test each.
Markdown version: /blueprints/structured-output-prompt.md
Want a deeper build of this?
Vote for an extended, fully tested version (more tools, a full workflow file). Votes decide what we build next.
Get one fully built blueprint a week
A weekly email: one blueprint with config, cost, setup time and failure modes, plus a vote on what we build next.
Related blueprints
Chain-of-Verification Fact Check Prompt
Draft an answer, generate verification questions, answer them independently, then revise, reducing factual errors.
Few-Shot Classification Prompt
A compact few-shot prompt for labeling text with balanced examples, an explicit label set, and an escape label.
Production Agent System Prompt Template
A sectioned system prompt template covering role, context, tools, rules, and output format for tool-using agents.