JSON Schema Generator
Paste a sample JSON object and instantly generate a JSON Schema that describes its structure.
minLength, pattern, format) for production use.
What is a JSON Schema Generator?
A JSON Schema generator is a tool that takes a sample JSON document and automatically produces a JSON Schema that describes its structure. JSON Schema is a powerful vocabulary that allows you to annotate and validate JSON documents. It defines the expected data types, which fields are required, the structure of nested objects and arrays, and additional constraints like minimum values, string patterns, and formats. Instead of writing a schema from scratch, a generator infers the schema from real data, saving time and reducing errors.
JSON Schema is used extensively in API development, configuration validation, and data contract testing. When you define a schema, you can validate incoming requests, ensure that configuration files are correct, and generate documentation automatically. A generator is particularly useful during the early stages of development when you have sample data but have not yet formalized the schema. It provides a solid starting point that you can refine with additional constraints.
Why Use a JSON Schema Generator?
Writing a JSON Schema by hand is tedious and error-prone. For a moderately complex object with nested structures, a schema can easily span hundreds of lines. A generator automates the mechanical work of inferring types and building the structure, allowing you to focus on the higher-level validation rules that matter. Here are the primary benefits:
- Speed: Generate a complete schema in seconds instead of minutes or hours. This is especially valuable when you have a large sample JSON with many fields.
- Accuracy: The generator analyzes the actual data types and structures in your sample, eliminating the risk of typos or mismatched types that can occur when writing a schema manually.
- Consistency: The generated schema follows a consistent structure and style, making it easier to read and maintain.
- Learning Aid: For developers new to JSON Schema, examining a generated schema is an excellent way to learn how types, properties, and required fields are represented.
How JSON Schema Inference Works
The generator walks through the sample JSON recursively and builds a schema for each value. The inference rules are straightforward but powerful:
- Primitives: Strings become
{"type": "string"}, numbers become{"type": "number"}(or"integer"if there is no decimal part), booleans become{"type": "boolean"}, and null becomes{"type": "null"}. - Objects: Each key-value pair in an object becomes a property in the schema. The
propertieskeyword holds the schema for each key. If the "Required Fields" option is enabled, all keys present in the sample are added to therequiredarray. - Arrays: The generator examines the items in the array. If all items are of the same type, it produces an
itemsschema for that type. If the array contains mixed types (e.g., a string and a number), it produces a schema usinganyOforoneOfto accommodate multiple possible types. This is a critical feature because real-world data often contains heterogeneous arrays. - Nested Structures: The process is applied recursively, so nested objects and arrays of objects are fully described. The generator does not flatten the structure; it preserves the hierarchy exactly as it appears in the sample.
This tool supports both Draft-07 and the newer 2020-12 specification. The primary difference is the $schema URI, but some keywords have been updated in 2020-12. The generator produces a schema that is valid for the selected draft, ensuring compatibility with modern validators.
Common Use Cases for JSON Schema
JSON Schema is used wherever JSON data needs to be validated or documented. Here are the most common scenarios:
- API Request Validation: When building a REST API, you can use a JSON Schema to validate the body of incoming requests. If a client sends malformed data, the validator rejects the request with a clear error message, preventing invalid data from entering your system.
- Configuration Validation: Many applications use JSON for configuration files. A JSON Schema ensures that the configuration file has the correct structure and types before the application starts, catching errors early.
- Data Contract Testing: In microservices architectures, services communicate via JSON. A schema defines the contract between services, and tests can validate that the actual payloads conform to the schema.
- Documentation: A JSON Schema is a machine-readable description of your data. It can be used to generate human-readable documentation automatically, keeping docs in sync with the code.
Limitations of Automated Inference
While a generator is a powerful starting point, it is important to understand its limitations. The inferred schema is based solely on the sample data provided. If the sample does not include a particular field or a particular type variation, the schema will not include it. For example, if a sample string happens to be a valid email address, the generator will infer {"type": "string"} but will not automatically add "format": "email". Similarly, if an array contains only one item, the generator cannot know whether the array will always contain that many items or if it is variable. These constraints must be added manually by reviewing the generated schema and refining it based on your domain knowledge.
How to Use This Tool
- Paste Your Sample JSON: Insert a representative JSON object into the input textarea. The more complete the sample, the more accurate the generated schema will be.
- Choose Draft Version: Select Draft-07 (the most widely supported) or 2020-12 (the latest specification).
- Set Required Fields: Choose whether to mark all keys present in the sample as required. If you are unsure, it is safer to mark them as required and relax the constraint later.
- Generate: Click "Generate Schema". The tool will parse the JSON and produce a formatted schema.
- Review and Refine: Copy the schema and add any missing constraints, formats, or patterns that your domain requires. Test the schema with a validator to ensure it behaves as expected.
Frequently Asked Questions
Is my JSON data sent to a server?
No. This tool runs entirely in your browser using client-side JavaScript. Your sample JSON never leaves your device and is not logged or stored anywhere. It is 100% private and safe for sensitive data.
What is the difference between Draft-07 and Draft 2020-12?
Draft-07 is the most widely supported version of JSON Schema and is compatible with most validators and tools. Draft 2020-12 is the latest specification and includes updated keywords and a different $schema URI. This tool supports both, so you can choose the version that matches your validator.
How does the tool handle arrays with mixed types?
If an array contains items of different types (e.g., a string and a number), the generator uses anyOf to describe the possible types. This ensures that the schema allows all variations present in the sample. For example, ["hello", 42] produces an items schema of {"anyOf": [{"type": "string"}, {"type": "number"}]}.
Why are all fields marked as required?
The "Required Fields" option is set to "Mark all present keys as required" by default. This means every key that appears in your sample JSON is added to the required array. If you want to make fields optional, change this option to "Do not mark any keys as required" and then add the required fields manually.
Can the generator infer string formats like email or date?
No. The generator infers only the basic JSON type (string, number, boolean, object, array, null). It does not automatically add format keywords like email, date-time, or uri, because these cannot be reliably inferred from a single sample. You should add these constraints manually based on your knowledge of the data.
What happens if my JSON contains null values?
A null value is inferred as {"type": "null"}. If a field can be null or another type, you should update the schema to use anyOf or oneOf to allow both possibilities. The generator produces a schema that matches the sample exactly, so if the sample contains null, the schema will expect null.
Does this tool support nested objects and arrays?
Yes. The generator recursively processes nested objects and arrays, preserving the full hierarchy. Each nested object is described in the properties of its parent, and arrays of objects are described using the items keyword with an object schema.
Can I generate a schema for a JSON array at the root?
Yes. If you paste a JSON array (e.g., [{"id": 1}, {"id": 2}]), the generator will produce a schema with {"type": "array", "items": { ... }}. It will infer the item schema from the objects in the array. If the array contains mixed types, it will use anyOf as described above.
What is the maximum JSON size I can process?
The limit depends on your browser's memory. Most modern browsers can handle JSON objects of several megabytes without issue. For extremely large files (e.g., >10MB), a command-line tool like jsonschema-generator might be more appropriate.
Does this tool validate the generated schema?
No. The tool generates a schema based on the sample JSON, but it does not validate the schema against the JSON Schema specification. It is always recommended to run the generated schema through a validator to ensure it is syntactically correct and behaves as expected.
Can I use this schema with OpenAPI or Swagger?
Yes. JSON Schema is a subset of the OpenAPI Schema Object. The generated schema (especially Draft-07) is compatible with OpenAPI 3.0 and later. You can paste it directly into the schema section of an OpenAPI component.
What is the difference between anyOf and oneOf?
anyOf means the value must match at least one of the schemas. oneOf means the value must match exactly one of the schemas. This tool uses anyOf for mixed-type arrays because a value can match multiple types in some cases (e.g., a number is also a valid number and integer).
Does the tool work offline?
After the page loads, the tool works offline because all parsing and generation run in your browser. You can disconnect from the internet and continue generating schemas.
Can I edit the generated schema directly in the output area?
The output area is read-only to prevent accidental changes. Use the "Copy Schema" button to copy the schema to your clipboard, then paste it into your editor to make modifications.
What happens if my JSON is invalid?
The tool will display an error message indicating the parsing failure. Common issues include trailing commas, missing quotes, or unescaped characters. Fix the JSON and try again.
Can I generate a schema for a JSON Lines (NDJSON) file?
No. This tool expects a single JSON object or array. If you have NDJSON (one JSON object per line), you would need to combine the lines into an array first or use a dedicated NDJSON schema generator.
Is this tool free to use?
Yes. It is completely free, requires no sign-up, and has no usage limits. All processing is local, so there are no server costs.
Can I use this tool on my phone?
Yes. The interface is fully responsive and works on mobile browsers. However, for large JSON files, a desktop browser is recommended for better performance.
What is the $schema keyword?
The $schema keyword declares which version of the JSON Schema specification the schema uses. It is a URI that points to the meta-schema. This tool automatically adds the correct $schema URI based on your draft selection.
Why does the schema use "type": "integer" for some numbers?
The generator checks whether a number has a decimal part. If it does not (e.g., 42), it infers "integer". If it does (e.g., 3.14), it infers "number". This provides a more precise schema. If you want all numbers to be treated as "number", you can manually change "integer" to "number".
Can I generate a schema from multiple JSON samples?
This tool accepts a single sample. To generate a schema that covers multiple samples, you would need to merge them or use a more advanced tool that supports multiple samples. The generated schema is based solely on the structure of the provided sample.
What library does this tool use under the hood?
This tool uses a custom, lightweight schema inference engine written in vanilla JavaScript. It implements the core JSON Schema specification (types, properties, required, items, anyOf) and produces valid schemas for Draft-07 and 2020-12.
No comments:
Post a Comment