Advanced Prompt Engineering / Output Control & Format

JSON Schema

Intermediate [3/5]
Schema validation Format enforcement

Definition

JSON Schema specifies the exact JSON structure that model output must follow. It defines field names, data types, required properties, and validation rules that ensure output consistency.

Many LLM APIs now support native JSON Schema enforcement, guaranteeing that outputs conform to specified structures.

Key Concepts

  • Type definitions: string, number, boolean, array, object
  • Required fields: Properties that must be present
  • Enum constraints: Fields limited to specific values
  • Nested objects: Complex hierarchical structures

Examples

Basic Schema
Type Definitions
{ "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"}, "email": {"type": "string", "format": "email"}, "active": {"type": "boolean"} }, "required": ["name", "age"] }
Complex Schema
Nested Structure with Enums
{ "type": "object", "properties": { "sentiment": { "type": "string", "enum": ["positive", "negative", "neutral"] }, "confidence": { "type": "number", "minimum": 0, "maximum": 1 }, "keywords": { "type": "array", "items": {"type": "string"}, "maxItems": 5 } }, "required": ["sentiment", "confidence"] }

Interactive Exercise

Fix the Schema

This schema has issues. What's wrong with it?

{"name": string, age: "number"}

Pro Tips
  • Use enums to constrain fields to specific values
  • Set minimum/maximum for numbers when appropriate
  • Mark truly required fields to catch missing data
  • Test schemas with edge cases before deployment

Related Terms