Manuals / Prompt Engineering / Ch 8

B · PatternsIntermediate35 min read

8. Structured output: JSON mode & schemas

Prompt Engineering · 48 pages source format

When downstream code consumes model output, free text is fragile. Use JSON mode, schemas, or XML tags for parseable results.

What you'll learn

  • JSON mode
  • Schema validation
  • XML tags

JSON extraction prompt

Define the exact schema. Ask for JSON only. Validate with a parser.

{
  "test_cases": [
    {
      "id": "TC-001",
      "title": "Login with valid credentials",
      "steps": ["Navigate to /login", "Enter valid user/pass", "Click Submit"],
      "expected": "Dashboard loads"
    }
  ]
}

Do this now

Extract test cases from a paragraph into JSON array. Parse with JSON.parse().

Clear?

Handle parse failures

Models sometimes wrap JSON in markdown fences. Strip fences. Retry with "JSON only, no markdown."

Do this now

Write a 5-line parser that handles fenced and raw JSON.

Clear?

Checklist