惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
T
The Blog of Author Tim Ferriss
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
L
LangChain Blog
博客园_首页
Vercel News
Vercel News
月光博客
月光博客
B
Blog RSS Feed
S
SegmentFault 最新的问题
博客园 - Franky
C
Check Point Blog
A
About on SuperTechFans
Stack Overflow Blog
Stack Overflow Blog
J
Java Code Geeks
F
Fortinet All Blogs
Recent Announcements
Recent Announcements
Y
Y Combinator Blog
罗磊的独立博客
D
Docker
酷 壳 – CoolShell
酷 壳 – CoolShell
云风的 BLOG
云风的 BLOG
人人都是产品经理
人人都是产品经理
WordPress大学
WordPress大学

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
JSON Schema Explained: Validate Your API Data Before It B...
Snappy Tools · 2026-05-25 · via DEV Community

Snappy Tools

You've seen this before: a frontend sends a request, the backend crashes, and the logs say TypeError: Cannot read properties of undefined. The payload was missing a required field, or a number arrived as a string. JSON Schema exists precisely to stop this class of bugs before they reach production.

This guide explains what JSON Schema is, how to write one, and how to validate JSON data against it — right in your browser.

What Is JSON Schema?

JSON Schema is a vocabulary that describes the structure of JSON data. It's itself written in JSON and defines:

  • What fields are required
  • What type each field should be (string, number, boolean, array, object, null)
  • Constraints like minimum/maximum values, pattern matching, and array lengths
  • Nested object structures

Think of it as a contract between a data producer (your API, your database, your user input) and a data consumer (your backend, your frontend, your analytics pipeline).

A Minimal Example

Here's a schema for a user profile object:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["id", "email", "age"],
  "properties": {
    "id": {
      "type": "string",
      "description": "UUID v4 identifier"
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "name": {
      "type": "string",
      "maxLength": 100
    }
  }
}

And here's JSON that validates against it:

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "user@example.com",
  "age": 28,
  "name": "Alex"
}

This JSON would fail validation:

{
  "id": 12345,
  "age": "twenty-eight"
}

Two errors: id should be a string, age should be an integer (and email is missing entirely).

Core JSON Schema Keywords

type

The most fundamental constraint. Allowed values: string, number, integer, boolean, array, object, null.

{ "type": "string" }
{ "type": ["string", "null"] }  // nullable field

required

An array of property names that must be present in the object.

{
  "type": "object",
  "required": ["username", "password"]
}

properties

Defines the schema for each named property.

String constraints

{
  "type": "string",
  "minLength": 8,
  "maxLength": 64,
  "pattern": "^[a-zA-Z0-9_]+$"
}

Number constraints

{
  "type": "number",
  "minimum": 0,
  "maximum": 100,
  "multipleOf": 0.01
}

Array constraints

{
  "type": "array",
  "items": { "type": "string" },
  "minItems": 1,
  "maxItems": 10,
  "uniqueItems": true
}

enum

Restricts a field to a specific set of allowed values:

{
  "type": "string",
  "enum": ["draft", "published", "archived"]
}

Nested Objects

Schemas can describe deeply nested structures. Here's an order item:

{
  "type": "object",
  "required": ["orderId", "items", "total"],
  "properties": {
    "orderId": { "type": "string" },
    "items": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["sku", "quantity"],
        "properties": {
          "sku": { "type": "string" },
          "quantity": { "type": "integer", "minimum": 1 },
          "price": { "type": "number", "minimum": 0 }
        }
      }
    },
    "total": { "type": "number", "minimum": 0 }
  }
}

Schema Composition: allOf, anyOf, oneOf

JSON Schema lets you combine schemas:

  • allOf — the data must be valid against all listed schemas
  • anyOf — the data must be valid against at least one
  • oneOf — the data must be valid against exactly one
{
  "oneOf": [
    { "type": "string", "maxLength": 5 },
    { "type": "number", "minimum": 0 }
  ]
}

This accepts either a short string or a non-negative number — but not both.

Where to Use JSON Schema

API validation — Validate request bodies before processing them. Libraries like ajv (Node.js) and jsonschema (Python) implement the full spec.

Configuration files — Many tools (VS Code, Prettier, ESLint) use JSON Schema to provide autocomplete and validation in config files.

Database documents — MongoDB supports JSON Schema validation natively in collection rules.

CI pipelines — Validate data files, API responses, or config changes as part of your build.

OpenAPI/Swagger — OpenAPI 3.x uses JSON Schema to describe request and response bodies. Understanding JSON Schema means understanding your API docs.

Validate JSON Against a Schema Right Now

Instead of setting up a library locally, you can paste your JSON and schema into the JSON Schema Validator on SnappyTools — it runs entirely in your browser using the ajv library (the most compliant validator available), supports JSON Schema draft-07 and 2020-12, and gives you line-by-line error messages.

Useful when you're:

  • Debugging why a payload is failing validation
  • Testing a schema you're writing for the first time
  • Checking a third-party API response against expected structure

Quick Reference

Keyword Purpose
type Data type constraint
required Mandatory properties
properties Property schemas
enum Allowed values list
minimum / maximum Number range
minLength / maxLength String length
pattern Regex constraint on string
items Schema for array elements
minItems / maxItems Array length
allOf / anyOf / oneOf Schema composition
$ref Reference to another schema

Conclusion

JSON Schema is one of those tools that feels like extra work until the first time it catches a production bug before it ships. A well-written schema documents your data structure, validates it automatically, and gives teammates a clear contract to code against.

Start with type and required, then add constraints as needed. Use the online validator to test as you go.


SnappyTools builds free, fast, browser-based tools for developers. No signup, no data uploaded.