JJSONForge
Get JSONForge

JSONForge/Guides

JSON Schema Generator Example: From Sample to Spec

Learn how to generate a JSON Schema from sample data using JSONForge. Follow a step-by-step example to create valid specs for your API.

October 15, 2026 · 5 min read

A JSON schema generator converts a sample JSON document into a formal schema definition by inferring types, required fields, and structure automatically. This saves time compared to writing schemas by hand, ensuring your API documentation matches real-world data patterns immediately. You paste your sample JSON into a tool, receive a structured schema draft, and refine it for your specific validation needs.

Why Generate Schema from Sample?

Writing JSON Schema definitions manually is tedious and error-prone, especially for complex nested structures. Developers often forget optional fields or misconfigure type constraints when starting from scratch. Generating a schema from an actual JSON sample ensures the specification reflects reality rather than assumption. This approach captures the exact shape of your data, including nested objects and arrays, providing a solid foundation for validation.

When you generate a schema from a sample, the tool analyzes the structure to determine if fields are strings, numbers, booleans, objects, or arrays. It identifies which fields appear consistently across the sample to mark them as required. This initial draft is rarely perfect, but it provides a significant head start. You then adjust constraints, add descriptions, and handle edge cases manually. This workflow balances speed with precision, allowing you to focus on business logic rather than syntax formatting.

Step 1: Prepare Your Sample JSON

The quality of your generated schema depends heavily on the quality of your input sample. A good sample should represent typical data as well as edge cases you expect to encounter. Include null values if they are valid, empty arrays if they occur naturally, and mixed types if your API supports them. However, avoid including irrelevant metadata or excessive repetition that might confuse the inference logic.

Consider this realistic user profile JSON representing a typical API response:

{
  "id": 1042,
  "name": "Alex Rivera",
  "active": true,
  "tags": ["admin", "editor"],
  "address": {
    "street": "123 Maple Ave",
    "city": "Springfield",
    "zip": "12345",
    "coordinates": [40.7128, -74.0060]
  },
  "lastLogin": "2023-10-27T10:00:00Z"
}

Notice how this sample includes a mix of primitives, a string array, a nested object, and a numeric array. It also includes a date string in ISO format. This variety helps the generator infer accurate types. If your real data sometimes omits the middleName field, include that variation in a second sample if the tool supports multiple inputs, or manually add it as optional later. Ensure your JSON is valid before pasting it; trailing commas or missing quotes will break the parsing process.

Step 2: Generate Schema with JSONForge

Once your sample is ready, you need a tool to convert it into JSON Schema. JSONForge offers a dedicated "Schema from sample" feature that runs entirely in your browser. This ensures your data remains private while processing occurs instantly without server round-trips. Paste your prepared JSON into the input area and select the schema generation option. The tool analyzes the structure and produces a draft schema compatible with modern standards.

The output will look structured and hierarchical, mirroring your input. For the user profile example above, the generated schema will define an object with properties corresponding to each key. It will infer that id is a number, name is a string, and active is a boolean. Arrays like tags will be defined as arrays of strings. Nested objects like address will be defined as nested objects with their own properties.

Here is the exact schema output you would expect from the sample above:

{
  "type": "object",
  "properties": {
    "id": {
      "type": "number"
    },
    "name": {
      "type": "string"
    },
    "active": {
      "type": "boolean"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "address": {
      "type": "object",
      "properties": {
        "street": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "zip": {
          "type": "string"
        },
        "coordinates": {
          "type": "array",
          "items": {
            "type": "number"
          }
        }
      }
    },
    "lastLogin": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "name",
    "active",
    "tags",
    "address",
    "lastLogin"
  ]
}

This output is ready for immediate use. It captures the structure accurately and marks all present fields as required, which is the default assumption when generating from a single sample.

Step 3: Review and Refine the Output

The generated schema is a starting point, not the final product. You must review it against your actual business requirements. The automatic inference makes reasonable guesses, but it cannot know if zip should be validated as a specific pattern or if lastLogin must be in ISO 8601 format specifically. These nuances require manual adjustment.

Start by checking the required array. If your API allows omitting middleName or phone, ensure those fields are not listed as required. In the example above, all fields were present in the sample, so all are marked required. If middleName was absent in some records, you would remove it from the required list and potentially add a default value or allow null.

Next, refine type constraints. The generator inferred coordinates as an array of numbers. This is correct, but you might want to specify that it always contains exactly two numbers. You can add minItems and maxItems constraints to the array definition. Similarly, for zip, you might add a pattern regex to enforce a specific format if your region requires it.

AspectAuto-GeneratedRecommended Refinement
TypesBasic (string, number)Add formats (date-time, email)
Required FieldsAll present keysOnly mandatory business fields
ArraysItems type inferredAdd min/max item counts
StringsSimple stringAdd minLength/maxLength or pattern

Handling Nested Objects and Arrays

Nested structures are common in API responses, and handling them correctly in schemas is crucial for validation accuracy. The generator handles nesting automatically by creating nested properties objects within the parent property definition. This mirrors the JSON structure exactly. For example, the address object in our sample becomes a nested object schema inside the main root object schema.

Arrays require special attention because their content definition lives in the items keyword. If an array contains objects, the items value becomes an object schema. If it contains primitives, it becomes a primitive type definition. In our example, tags is an array of strings, so items is {"type": "string"}. The coordinates array contains numbers, so items is {"type": "number"}.

Sometimes arrays contain mixed types or complex objects. If your sample had an array of mixed strings and numbers, the generator might infer a union type or a generic type depending on the tool's sophistication. JSON Schema draft 2020-12 supports union types via anyOf or oneOf. If the generated schema is too loose, tighten it manually. For instance, if tags must always contain lowercase alphanumeric strings, add a pattern constraint to the items definition.

Deeply nested objects can become verbose. Keep nesting levels reasonable for readability. If you have a three-level deep structure, ensure each level has clear property names. The schema generator preserves this hierarchy, so your final spec will be readable. Avoid excessive nesting in your JSON samples if possible, as it complicates the schema and the validation logic.

Finalizing Your API Specification

Once you have refined your schema, integrate it into your development workflow. You can paste the final JSON Schema directly into your OpenAPI specification file under the relevant component or response definition. Most backend frameworks and API documentation tools accept JSON Schema directly. This ensures that the documentation matches the validation rules exactly.

Test the schema against real payloads to ensure it behaves as expected. Use a validator to check a few known-good and known-bad examples. If the validator rejects valid data, loosen the constraints. If it accepts invalid data, tighten them. This iterative process ensures your schema is robust.

Keep your schema in version control alongside your code. As your API evolves, update the schema to reflect new fields or changed types. Regenerating the schema from an updated sample is quick and ensures consistency. For teams, this reduces friction in API design reviews. The schema becomes a living document that evolves with the codebase.

By starting with a sample and refining the output, you create accurate, maintainable schemas without the overhead of writing them from scratch. This approach leverages automation for structure while retaining human control over business rules. The result is a reliable validation layer that supports your API's integrity.

Do it in JSONForge

Everything in this guide works in the browser — open the tool and try it on your own input.

Open JSONForge →

Questions people also ask

Does JSONForge support JSON Schema draft 2020-12?

Yes, JSONForge generates schemas compatible with modern standards, including Draft 2020-12. The output uses standard keywords like `type`, `properties`, and `required` that are fully supported in this version.

Can I edit the generated schema before saving?

Yes, you can manually refine the generated schema after creation. This allows you to adjust constraints, add descriptions, or mark fields as optional to better match your specific validation needs.

Does my JSON data leave my browser during generation?

No, processing occurs entirely within your browser. This ensures your data remains private and is processed instantly without requiring server round-trips.

More guides