Prompt Engineering JSON Output Force JSON

Force JSON Output from AI

Stop getting 'Sure, here is the JSON…' — the output-contract pattern that forces models to return only parseable JSON: schema, example, and a strict rule block.

Overview

Asking for JSON politely fails in three ways: the model wraps the object in prose, fences it in markdown, or invents fields you never asked for. Forcing JSON reliably takes a contract, not a request: a schema with explicit types and requirements, a realistic example response the model can imitate, validation rules for nulls and types, and a strict rule block that bans everything except the object itself. This resource loads a complete strict-mode contract so you can see all four parts working together — then adapt the schema to your own data.

Workflow

  1. Open the loaded contract

    The customer-record schema loads in Strict mode. Generate and read the four sections — each handles a different failure mode.

  2. Swap in your fields

    Replace the schema fields with your own; the example response regenerates with realistic values automatically.

  3. Test at Standard first

    If your model behaves, Standard's four rules cost fewer tokens. Escalate to Strict only when prose leaks through.

Why This Works

  • The example response does more than the rules — models imitate examples more faithfully than they follow instructions
  • Explicit null discipline kills the two worst failure modes: omitted keys and invented values
  • The strict block addresses each leak (prose, fences, commentary, extra objects) by name instead of saying 'only JSON' and hoping

Best for

  • Developers parsing model output in code
  • Automations that crash on markdown fences and trailing text
  • Anyone whose JSON requests come back as friendly paragraphs

Not for

  • Checking output you've already received — that's the AI Output Validator
  • Models with native structured output where syntax is guaranteed — though the schema rules still apply

Use cases

  • Making a chat model's output safe to JSON.parse without cleanup code
  • Hardening an API integration that breaks on prose-wrapped responses
  • Replacing 'return valid JSON' one-liners with a contract that actually holds

Tip: Save time by exploring related resources and tools that integrate with this workflow.

Explore all resources