A flat schema cannot express a reply with grouped fields, such as an address inside a customer record, or a list of steps inside a solution. JSON Schema supports nested objects and arrays of objects, and the OpenAI function calling guide notes that parameters defined by JSON Schema can use nested objects and recursive objects. The OpenAI structured outputs guide shows the same pattern in its worked example: a MathReasoning object holding a list of Step objects, each with an explanation and an output, plus a final answer.
What you need
- The reply shape, sketched as grouped fields
- The field names and types for each level
- A validator to check a sample reply against the schema
Step 1: Define the outer object first
Write the top-level object with its properties and its required list. Keep the top level small: it should name the groups, not hold every detail.
Step 2: Nest an object or a list of objects inside it
Define each group as a nested object with its own properties and required list, or as an array of objects when the group repeats, such as a list of steps. Each nested object is validated on its own, so an error points at the right level.
Step 3: Validate a sample reply against the schema
Generate a sample reply and validate it with a JSON Schema validator. If the model omits a nested required field, add the field to the required list at the right level and re-test, rather than loosening the schema.
Worked example: synthetic nested schema check
The table below is a synthetic example. It shows the expected result of validating a nested reply; no model was run.
| Level | Fields | Valid? |
|---|---|---|
| Customer | name, address | Yes |
| Address | street, city, postcode | Yes |
| Order | items list | Yes |
| Item | name, quantity | Yes |
Expected result (UNTESTED). the reply validates at every level, with the address nested inside the customer and items nested inside the order. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- Deep nesting makes schemas harder for the model to follow: keep the depth as shallow as the data allows.
- Structured Outputs supports a subset of JSON Schema, so check the supported schema list before using an exotic keyword.
- A nested object that is optional should be marked as such, or the model will invent it to satisfy the schema.
- Validate with a real validator: reading the reply by eye misses a missing nested field.
