New Tool Radar

AI Concepts

How to Get JSON Matching a Schema from a Model with Structured Outputs

Get JSON that matches your schema every time by sending a JSON Schema with Structured Outputs.

Schematic illustration of get json matching a schema from a model with structured outputs: step one write the schema, step two send it as response format, step three parse the reply.

Structured Outputs constrains a model’s completed, non-refusal output to the JSON Schema you supply, so required fields and enum values follow the schema you defined. That is the difference from asking for JSON in plain words: a prompt can be ignored, but a schema is enforced. Use it whenever your code must parse the reply.

Prerequisites

  • Access to an API that supports Structured Outputs, starting with GPT-4o and later models.
  • A JSON Schema for the reply you want.
  • A JSON parser in your code to read the reply.

Steps

Step 1: Write the schema

Define the reply as a JSON Schema: an object with named properties, types, required fields and, where the values are fixed, an enum. Keep it small: every field you add is a field the model must fill.

Step 2: Send it as the response format

Send the schema as the response format of the request (json_schema in Chat Completions, or text.format in the Responses API). Do not also ask for JSON in the prompt text; the schema already carries the requirement.

Step 3: Parse the reply

Parse the reply as JSON and check it against the schema in code. Structured Outputs guarantees the shape, not the truth of the values, so validate any business rule the schema cannot express.

Worked example: Maple Corner bakery order summary

The fictional Maple Corner bakery asks a model to summarise an order as JSON with three fields: item, quantity and total.

Field Type Required Example value
item string Yes sourdough loaf
quantity integer Yes 12
total number Yes 54.00

The reply is a JSON object with all three fields, item ‘sourdough loaf’, quantity 12 and total 54.00, and it parses without repair.

Expected result. The reply parses as JSON on the first try and matches the schema, with no extra text before or after it. UNTESTED: this guide was not run against a live model or API. The worked example below is fictional practice material, and its result is the expected result, not a measured one.

Limits

  • Structured Outputs still allows refusals and incomplete responses, so your code must handle those cases.
  • Only a subset of JSON Schema is supported; check the guide for the supported subset before writing a complex schema.
  • Shape is guaranteed, meaning is not: a wrong total can still pass schema validation.

Sources

See all