Reliable Structured JSON Output Pattern

Get valid, schema-conforming JSON from any model using native structured outputs where available, and validate-and-repair otherwise.

jsonschemavalidationextraction
Setup time30 minutes (estimate)
Estimated costRepairs add an extra call only on failures.
ToolsPython
VerificationNot yet independently verified

Order of preference

  1. Native structured outputs (e.g. OpenAI response_format: {type: "json_schema", ...} with strict: true, or tool calling with a schema).
  2. JSON mode plus schema in the prompt.
  3. 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

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.

– votes

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