How to generate a JSON Schema from JSON

Writing a JSON Schema by hand is slow. A generator reads a sample and writes the schema in a second. The result describes that one sample, so it needs a short review before it describes your data.

Updated

Generate the schema

  1. Pick a sample that has every field filled in. A generator cannot describe a field it never sees.
  2. Paste the sample into the generator and run it.
  3. Copy the schema into your project.

What you get

This sample:

{ "id": 1, "name": "Ada", "tags": ["new"] }

The generated schema

Every field is typed, every field is required, and unknown fields are rejected. That is the strict shape that LLM structured outputs need.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "GeneratedSchema",
  "type": "object",
  "properties": {
    "id": { "type": "integer" },
    "name": { "type": "string" },
    "tags": { "type": "array", "items": { "type": "string" } }
  },
  "required": ["id", "name", "tags"],
  "additionalProperties": false
}

Six things to fix by hand

  • Required fields. The generator marks all of them as required. For API validation, remove the optional ones from the list. For OpenAI Structured Outputs, leave the list alone, because every field must be required there.
  • Nullable fields. If a value can be null, change its type to a list such as ["string", "null"].
  • Arrays. The generator reads the first element only. Check that the other elements have the same shape.
  • Fixed values. A field such as status has a short list of valid values. Replace the string type with an enum.
  • Limits and formats. Add minimum, maximum, minLength or a format such as email or date-time where the data has rules.
  • Descriptions. Add a description to each field. A language model reads them as instructions, and so does the next developer.

Test the schema

Generate sample data from the finished schema and read it. If a record looks wrong, such as a negative price or an empty list of items, the schema allows too much.

Then run a real document through a validator, such as Ajv in JavaScript or jsonschema in Python.

Using the schema with an LLM

OpenAI, Anthropic and Google all accept a JSON Schema to fix the format of a model's answer. Each supports a subset of the keywords. Types, properties, required, enum and descriptions work everywhere. Check the provider's documentation before you rely on limits such as minimum or pattern.

Tools for this guide

All tools →

More guides

All guides →