You can generate a JSON Schema by pasting representative JSON samples into a schema generator, which infers types and required fields automatically. The resulting schema defines the expected structure of your data, allowing you to validate future payloads against this shape. This method is faster than writing schemas by hand, particularly for deeply nested objects or complex arrays.
Why Generate Schema from Sample Data?
Writing JSON Schema manually is tedious and prone to errors, especially when dealing with deeply nested structures. A generated schema captures the exact shape of your data at a specific moment, providing a reliable baseline for validation. This is useful for documenting API responses, configuring frontend form validations, or ensuring backend consistency. Instead of guessing which fields are optional or what types are expected, the generator derives these constraints directly from real data examples. This ensures your schema reflects actual data patterns rather than assumptions, reducing debugging time later in the development cycle.
Prepare Your JSON Payload
The quality of your generated schema depends on the quality of your sample JSON and the inference rules of the generator. You need a payload that covers all possible variations of your data structure. If your API sometimes returns null values or empty arrays, include examples that demonstrate these cases. If certain fields are optional, ensure your sample reflects that reality. For instance, if a user profile might lack a middle name, include an example without it so the generator marks that field as optional rather than required. Avoid using minimal or overly simplified examples, as these often produce incomplete schemas that reject valid data later.
Consider this realistic user profile example, which includes nested objects and arrays:
{
"id": 101,
"name": "Jane Doe",
"email": "[email protected]",
"roles": ["admin", "editor"],
"address": {
"street": "123 Main St",
"city": "Springfield",
"zip": "12345"
},
"preferences": {
"theme": "dark",
"notifications": true
}
}
This payload contains integers, strings, arrays of strings, and nested objects. It represents a typical API response structure. Notice that all fields are present. If you know middle_name is optional, add a second sample or adjust this one to include it as null or omit it, depending on your validation goals.
Generate the Schema Instantly
Once your sample JSON is ready, paste it into a schema generator. Look for a feature labeled "Schema from sample" or similar. The tool will parse the JSON and infer types for each key. For the example above, the generator identifies id as an integer, name and email as strings, roles as an array of strings, and address and preferences as objects. It also determines that all fields are required because they appear in the sample.
Using JSONForge’s Schema from sample feature, paste the JSON above and select JSON Schema draft 2020-12. The output will look like this:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"email": {
"type": "string"
},
"roles": {
"type": "array",
"items": {
"type": "string"
}
},
"address": {
"type": "object",
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
},
"zip": {
"type": "string"
}
},
"required": [
"street",
"city",
"zip"
]
},
"preferences": {
"type": "object",
"properties": {
"theme": {
"type": "string"
},
"notifications": {
"type": "boolean"
}
},
"required": [
"theme",
"notifications"
]
}
},
"required": [
"id",
"name",
"email",
"roles",
"address",
"preferences"
]
}
This schema strictly enforces the structure shown in the sample. Every field is marked required because every field appeared in the input. The nested objects have their own required lists, ensuring completeness at each level.
Validate and Refine the Output
Generated schemas are starting points, not final products. You must verify that the inferred constraints match your actual business logic. For example, if zip should only accept five-digit codes, the generated schema just says "type": "string". You need to manually add a pattern constraint. Similarly, if roles can only contain specific values, add an enum constraint.
Test the generated schema against real-world edge cases. Create a minimal valid payload and ensure it passes validation. Then create an invalid payload, such as missing the email field, and confirm it fails. This feedback loop helps you tune the schema. If you find that some fields are frequently missing in production but were present in your sample, adjust the required array accordingly. You can edit the JSON Schema directly or regenerate it with a more comprehensive sample.
For quick testing, paste both the schema and a test payload into a validator. JSONForge’s validator supports draft 2020-12 and provides clear pass/fail results with per-property error messages. This allows you to iterate quickly without leaving your browser.
Handle Optional Fields and Null Values
One common challenge is determining whether fields should be required or optional. The generator marks fields as required if they appear in the sample. If a field is sometimes absent, you must either include multiple samples or manually adjust the schema. For nullable fields, ensure your sample includes a null value so the generator infers "type": ["string", "null"] instead of just "string".
Consider this adjustment to the previous example where middle_name is optional:
{
"id": 102,
"name": "John Smith",
"middle_name": null,
"email": "[email protected]",
"roles": ["viewer"],
"address": {
"street": "456 Oak Ave",
"city": "Riverton",
"zip": "67890"
},
"preferences": {
"theme": "light",
"notifications": false
}
}
Generating a schema from this payload results in middle_name being typed as ["string", "null"]. If you omit middle_name entirely in some samples, the generator might mark it as optional or exclude it, depending on the tool’s logic. Always review the required array to ensure it matches your expectations.
Best Practices for Clean Schema Generation
Keep your sample data representative but concise. Avoid including unnecessary fields that clutter the schema. Use consistent formatting in your JSON samples to ensure accurate type inference. For example, always use double quotes for keys and strings, and avoid trailing commas, as these can cause parsing errors.
When dealing with arrays, ensure your sample includes at least one element to help the generator infer the item type. An empty array might result in a generic "items": {} definition, which is too permissive. If your array contains objects, include a fully populated object within the array to capture all properties.
For complex APIs, consider generating schemas for each endpoint separately. This keeps each schema focused and easier to maintain. Use descriptive property names in your JSON samples to make the generated schema self-documenting. Remember that generated schemas are often verbose; you can minify them for production use if size matters, but keep a readable version for documentation.
Finally, always validate your generated schema against your actual application data. Use tools like JSONForge to test real payloads against the schema before deploying. This catches mismatches early and ensures your validation rules work as intended.