Modern APIs, config files, databases — sab JSON deal karte hain. Lekin raw JSON schema-less hota hai — koi bhi key kisi bhi value hold kar sakti hai, aur consumer {"age": "twenty-five"} bhej sakta hai jab aap {"age": 25} expect kar rahe ho. JSON Schema is problem ko solve karta hai — JSON documents ki structure, types aur constraints describe karne ka vocabulary deta hai. Ek JSON Schema generator aapka sample JSON leta hai aur automatically ek Schema produce karta hai.
Is guide mein: JSON Schema kya hai aur draft versions kaise evolve hue, complete keyword reference real examples ke saath, schema generation algorithmically kaise kaam karta hai, advanced constraints jaise required, enum, pattern, aur OpenAPI/TypeScript ecosystem integration.
Apne JSON se Schema Generate Karo
Koi bhi JSON object paste karo aur instant valid JSON Schema paao. Draft 4, 7 aur 2020-12 support. Free, login required nahi.
JSON Schema kya hai aur Developers Ise Kyun Use Karte Hain?
JSON Schema ek declarative language hai JSON documents ko annotate aur validate karne ke liye. Current stable release Draft 2020-12 hai।
JSON Schema kya karta hai
- Validation — Runtime pe verify karo ki JSON data expected structure follow karta hai
- Documentation — Self-documenting API contracts jo humans aur machines dono read kar sakein
- Code generation — Schema se TypeScript interfaces, Python dataclasses, Go structs generate karo
- UI generation — react-jsonschema-form jaise tools schema se automatically forms render karte hain
- IDE support — JSON aur YAML files ko schema mila do toh autocomplete aur inline errors milenge
Simple Schema Example
// Sample JSON:
{
"id": 42,
"username": "jsmith",
"email": "jsmith@example.com",
"age": 30,
"active": true
}
// Generated JSON Schema (Draft 2020-12):
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"id": { "type": "integer" },
"username": { "type": "string", "minLength": 3, "maxLength": 30 },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0, "maximum": 150 },
"active": { "type": "boolean" }
},
"required": ["id", "username", "email"],
"additionalProperties": false
}
Draft Version History
| Draft | Year | Key Addition | Status |
|---|---|---|---|
| Draft 4 | 2013 | Foundation: type, properties, required, allOf/anyOf/oneOf | Legacy (widely used) |
| Draft 7 | 2018 | if/then/else, readOnly, writeOnly | Common in tools |
| Draft 2020-12 | 2020 | unevaluatedProperties, prefixItems, $dynamicRef | Current recommended |
JSON Schema Keywords: Complete Reference (Data Types aur Constraints)
Core Data Types
| Type | Example Values | Type-Specific Keywords |
|---|---|---|
string | "hello" | minLength, maxLength, pattern, format |
integer | 42, -7 | minimum, maximum, multipleOf |
number | 3.14, 42 | minimum, maximum, multipleOf |
boolean | true, false | — |
array | [1, 2, 3] | items, minItems, maxItems, uniqueItems |
object | {"key": "val"} | properties, required, additionalProperties |
null | null | — |
String Keywords — Practical Examples
{
"type": "string",
"minLength": 8,
"maxLength": 128,
"pattern": "^[A-Z]{2}\d{6}$",
"format": "email"
// Formats: email, uri, uuid, date, date-time, ipv4, ipv6, hostname
}
Conditional Keywords (Draft 7+)
{
"type": "object",
"properties": {
"accountType": { "enum": ["personal", "business"] },
"companyName": { "type": "string" }
},
"if": {
"properties": { "accountType": { "const": "business" } }
},
"then": {
"required": ["companyName"] // Business account mein company required
}
}
Validation Constraints: required, additionalProperties, enum aur pattern
required — Mandatory Fields
{
"type": "object",
"properties": {
"id": { "type": "integer" },
"email": { "type": "string", "format": "email" },
"password": { "type": "string", "minLength": 8 },
"nickname": { "type": "string" } // Optional — required mein nahi
},
"required": ["id", "email", "password"]
}
// VALID: { "id": 1, "email": "a@b.com", "password": "secret123" }
// INVALID: { "id": 1, "email": "a@b.com" }
// → "required property 'password' is missing"
additionalProperties — Object Shape Control
// Strict: unknown keys reject karo
{
"type": "object",
"properties": { "name": { "type": "string" } },
"additionalProperties": false
}
// INVALID: { "name": "Alice", "hackerField": "malicious" }
// Flexible: extra keys allowed but constrained
{
"additionalProperties": { "type": "string" }
}
pattern — Regex Validation
{
"username": { "pattern": "^[a-zA-Z0-9_]{3,30}$" },
"phone": { "pattern": "^\+91[6-9]\d{9}$" }, // Indian phone numbers
"hexColor": { "pattern": "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$" },
"slug": { "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" }
}
Common Mistake — properties ≠ required
// GALAT SAMAJH — properties sirf define karta hai, enforce nahi
{
"type": "object",
"properties": { "name": { "type": "string" } }
}
// {} is VALID! properties ki value abhi bhi optional hai.
// SAHI: required alag se likhna padta hai
{
"type": "object",
"properties": { "name": { "type": "string" } },
"required": ["name"]
}
API Development mein JSON Schema: OpenAPI, Swagger aur TypeScript
JSON Schema APIs ki description ka backbone hai। OpenAPI 3.1 ne JSON Schema Draft 2020-12 ke saath full alignment kiya hai।
OpenAPI 3.1 ke saath JSON Schema
openapi: 3.1.0
components:
schemas:
CreateUserRequest:
type: object
properties:
username:
type: string
minLength: 3
pattern: '^[a-zA-Z0-9_]+$'
email:
type: string
format: email
password:
type: string
minLength: 8
writeOnly: true # Sirf request mein, response mein nahi
required: [username, email, password]
additionalProperties: false
Node.js mein Ajv se Runtime Validation
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
const ajv = new Ajv({ allErrors: true });
addFormats(ajv);
const schema = {
type: "object",
properties: {
email: { type: "string", format: "email" },
age: { type: "integer", minimum: 0 }
},
required: ["email"]
};
const validate = ajv.compile(schema);
const data = { email: "not-valid", age: -5 };
if (!validate(data)) {
console.error(validate.errors);
// [
// { instancePath: '/email', message: 'must match format "email"' },
// { instancePath: '/age', message: 'must be >= 0' }
// ]
}
TypeScript Code Generation
# JSON Schema se TypeScript interfaces generate karo
npm install -g json-schema-to-typescript
json2ts -i user.schema.json -o user.types.ts
JSON Schema vs TypeScript Interfaces vs Zod: Kab Kya Use Karein
Comparison Table
| Feature | JSON Schema | TypeScript Interface | Zod |
|---|---|---|---|
| Runtime validation | Yes (Ajv) | No | Yes (built-in) |
| Compile-time types | Codegen se | Yes (native) | Yes (z.infer) |
| Language-agnostic | Yes | No | No |
| OpenAPI integration | Native | Via decorators | zod-to-openapi |
| Bundle size | Ajv ~30kb | Zero | ~8kb |
Decision Guide
JSON Schema use karo jab:
✓ Language-agnostic APIs (Go, Python consumers bhi hain)
✓ OpenAPI/Swagger documentation required hai
✓ Config files ke liye IDE support chahiye
✓ Form generation (react-jsonschema-form)
TypeScript Interface use karo jab:
✓ Pure TypeScript codebase, runtime validation needed nahi
✓ Performance-critical code
✓ Simple type annotation
Zod use karo jab:
✓ Next.js, tRPC, Remix fullstack apps
✓ Types aur runtime validation ek saath chahiye
✓ Form validation with great error messages
Zod se JSON Schema Generate Karo
import { z } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';
const UserSchema = z.object({
id: z.number().int().positive(),
username: z.string().min(3).max(30).regex(/^[a-zA-Z0-9_]+$/),
email: z.string().email(),
});
type User = z.infer; // TypeScript type
const jsonSchema = zodToJsonSchema(UserSchema); // JSON Schema for OpenAPI
Common JSON Schema Mistakes aur Validation Errors Fix Kaise Karein
Mistake 1: additionalProperties + allOf Bug
// GALAT (Draft 4-7 mein):
{
"allOf": [{ "$ref": "#/$defs/Base" }],
"additionalProperties": false // Sirf apni properties dekhta hai, Base ki nahi!
}
// SAHI (Draft 2020-12):
{
"allOf": [{ "$ref": "#/$defs/Base" }],
"unevaluatedProperties": false // Sab subschemas ki properties dekhta hai
}
Mistake 2: Pattern mein Double Escaping
// GALAT (JSON parse error):
{ "pattern": "^d{3}-d{4}$" }
// SAHI (double backslash in JSON string):
{ "pattern": "^\d{3}-\d{4}$" }
Mistake 3: Null vs Missing Property
// Absent: { "id": 1 } (key exist nahi karta)
// Null: { "id": 1, "bio": null } (key hai, value null hai)
// Dono allow karne ke liye:
{
"properties": {
"bio": { "type": ["string", "null"] } // Draft 2020-12 shorthand
}
// "bio" required[] mein nahi — absent bhi valid
}
$ref aur $defs se Schema Reuse
$defs se Reusable Components
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$defs": {
"Address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"pincode": { "type": "string", "pattern": "^[1-9][0-9]{5}$" }
},
"required": ["street", "city", "pincode"]
}
},
"type": "object",
"properties": {
"billingAddress": { "$ref": "#/$defs/Address" },
"shippingAddress": { "$ref": "#/$defs/Address" }
}
}
Iss approach se:
- Address schema ek jagah define hai — do jagah reuse hota hai
- Address change karne par dono references automatically update ho jaate hain
- Schema smaller aur maintainable rehta hai
How to Use the Tool (Step by Step)
- 1
Sample JSON paste karo
API response, config file ya database record se real JSON object copy karo aur input panel mein paste karo।
- 2
Draft version select karo
JSON Schema draft choose karo: naye projects ke liye Draft 2020-12, maximum tool compatibility ke liye Draft 7, legacy systems ke liye Draft 4।
- 3
Generation options configure karo
Choose karo: sab keys required mein rakhne hain ya nahi, string formats detect karni hain (email, URI, date-time), additionalProperties false karni hai ya nahi।
- 4
Schema generate karo
Generate click karo. Tool types infer karta hai, formats detect karta hai, nested structures identify karta hai aur 1 second mein complete valid JSON Schema produce karta hai।
- 5
Review aur refine karo
Generated schema starting point hai। Manually refine karo: optional fields required[] se remove karo, numbers ke liye minimum/maximum add karo, strings ke liye pattern tighten karo।
- 6
Sample data validate karo
Inline validator se schema ke against multiple JSON examples test karo। Production pe ship karne se pehle validation errors pakdo।
Frequently Asked Questions
JSON Schema Draft 4, 7 aur 2020-12 mein kya difference hai?+−
Draft 4 (2013) ne foundation set kiya — type, properties, required, allOf/anyOf/oneOf. Draft 7 (2018) ne if/then/else conditional validation, readOnly, writeOnly add kiya. Draft 2020-12 current standard hai: unevaluatedProperties (additionalProperties+allOf bug fix), tuples ke liye prefixItems, aur improved $ref semantics. New projects ke liye Draft 2020-12 use karo. Maximum tooling compatibility ke liye Draft 7 safe choice hai.
additionalProperties: false allOf ke saath kaise kaam karta hai?+−
Draft 4-7 mein additionalProperties sirf same schema object mein defined properties dekhta hai — $ref ya allOf sibling ki properties nahi dekhta. Yeh ek well-known bug hai. Fix: Draft 2020-12 mein unevaluatedProperties: false use karo jo sab referenced schemas ki properties correctly consider karta hai। Older drafts mein workaround: jis object mein additionalProperties: false hai usme sab property names manually repeat karo.
JSON Schema se TypeScript types kaise generate karein?+−
json-schema-to-typescript package (json2ts CLI) koi bhi JSON Schema file se TypeScript interfaces generate karta hai. Run karo: npm install -g json-schema-to-typescript && json2ts -i schema.json -o types.ts. Ya Zod ke saath zod-to-json-schema use karo — TypeScript mein ek single source of truth maintain karo jo types aur JSON Schema dono produce kare.
Node.js mein best JSON Schema validator library kaun si hai?+−
Ajv (Another JSON Validator) industry standard hai — fastest, most spec-compliant aur millions of packages use karte hain. Install: npm install ajv ajv-formats (email, uri, date-time format validation ke liye). Browser environments ke liye Ajv ka bundle ~30kb gzipped hai. Ajv version 8 by default Draft 2020-12 support karta hai.
Next.js ke liye JSON Schema use karein ya Zod?+−
TypeScript-only Next.js project ke liye Zod simpler hai — types aur runtime validation ek declaration se milte hain with excellent error messages. OpenAPI docs bhi chahiye toh zod-to-openapi package add karo. JSON Schema directly tab use karo jab language-agnostic validation chahiye, config files ke liye IDE schema support chahiye, ya non-TypeScript services aapki schemas consume karti hain.
Apne JSON se Schema Generate Karo
Koi bhi JSON object paste karo aur instant valid JSON Schema paao. Draft 4, 7 aur 2020-12 support. Free, login required nahi.
JSON Schema Generator KholeinRelated Guides
JSON फॉर्मेटर गाइड
JSON क्या है, कैसे format करें, common errors कैसे fix करें — developers और beginners दोनों के लिए।
JSON को CSV में Convert करें — Free Guide (2026)
JSON data को CSV/Excel format — API data export, sharing।
Base64 Encode & Decode — क्या है, कैसे काम करता है? (Developer Guide)
Base64 encoding की पूरी जानकारी — use cases, online decoder, और common pitfalls