New Tool Radar

AI Concepts

How to Write a JSON Schema With Types, Required Fields and Enums

Name the object, type every field, mark the required ones, and restrict fixed values with an enum before you send it to the model.

Schematic with three steps: Name the object and type every field; Mark the required fields; Restrict fixed values with an enum.

JSON Schema is the vocabulary that enables JSON data consistency, validity and interoperability at scale: you define constraints for your data structures to catch and prevent errors. A schema for structured output needs four things: the object type, a type for every field, a required list naming the fields that must always appear, and enums for fields that can only take fixed values. A schema that leaves a field untyped or forgets the required list lets the model omit or mistype the very data your code needs.

What you need

  • The fields the model must return and their types
  • Which fields are required and which are optional
  • The fixed values for any field that has only a few options

Step 1: Name the object and type every field

Write the schema with type object and a properties map, giving each field a type such as string, integer or array. A field with no type is a field the model can fill with anything.

Step 2: Mark the required fields

Add a required list with every field your code reads without a fallback. A field that is not required may be omitted, so do not list a field as required unless your code truly needs it.

Step 3: Restrict fixed values with an enum

For a field such as units, add an enum with the allowed values, for example celsius and fahrenheit. The model must then pick one of the listed values instead of inventing a new one.

Worked example: synthetic JSON Schema for a weather reply

The table below is a synthetic example. It shows the expected result of writing a schema; no call was made.

Field Type Rule
location string Required
units string Required, enum celsius or fahrenheit
temperature number Required
note string Optional

Expected result (UNTESTED). the schema types all 4 fields, requires 3 of them, and restricts units to the two allowed values. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • Structured outputs guarantee schema adherence, but they do not guarantee the facts inside the fields are true.
  • Only a subset of JSON Schema is supported by structured outputs; check the supported schemas list before using an exotic keyword.
  • A schema that is too strict can force the model to invent a value rather than admit it does not know; allow an explicit unknown value.
  • JSON Schema is a validation vocabulary, not a guarantee: your application must still handle refusals and incomplete responses.

Sources

See all