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

推荐订阅源

S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园_首页
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The GitHub Blog
The GitHub Blog
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
博客园 - 叶小钗
MongoDB | Blog
MongoDB | Blog
N
News and Events Feed by Topic
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Tailwind CSS Blog
Google DeepMind News
Google DeepMind News
IT之家
IT之家
W
WeLiveSecurity
P
Proofpoint News Feed
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
月光博客
月光博客
Schneier on Security
Schneier on Security
博客园 - 三生石上(FineUI控件)
Application and Cybersecurity Blog
Application and Cybersecurity Blog
腾讯CDC
H
Heimdal Security Blog
Y
Y Combinator Blog
Engineering at Meta
Engineering at Meta
量子位
宝玉的分享
宝玉的分享
博客园 - 【当耐特】
V
Visual Studio Blog
L
LangChain Blog
Last Week in AI
Last Week in AI
The Cloudflare Blog
Hacker News: Ask HN
Hacker News: Ask HN
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Security Archives - TechRepublic
Security Archives - TechRepublic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
SecWiki News
SecWiki News
Simon Willison's Weblog
Simon Willison's Weblog
Security Latest
Security Latest
A
Arctic Wolf
T
Tenable Blog
I
Intezer
P
Privacy International News Feed
Attack and Defense Labs
Attack and Defense Labs
N
News | PayPal Newsroom
Martin Fowler
Martin Fowler

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
JSON Schema in 10 Minutes — Validation, Types & Real Examples
Anh Quân Ngu · 2026-05-26 · via DEV Community

Two years ago I shipped a webhook handler without input validation. A partner started sending us a slightly malformed payload (an extra field, one missing required field) and our worker silently processed garbage into the database for three days before anyone noticed. By the time I traced it, we had 12,000 corrupt rows and a very awkward customer call.

I learned JSON Schema the next week. This post is the cheat sheet I wish someone had handed me on day one — the keywords I actually use, the gotchas that bit me again later, and the honest comparison with OpenAPI and TypeScript types.

The seven types you'll use

Every JSON value is one of seven types: string, number, integer, boolean, object, array, or null. The integer type is a JSON Schema convenience (raw JSON only has number) but the schema layer enforces "no decimal places." A minimal schema:

{
  "type": "string"
}

Enter fullscreen mode Exit fullscreen mode

That validates any string and rejects everything else. You can also accept a union:

{
  "type": ["string", "null"]
}

Enter fullscreen mode Exit fullscreen mode

Useful for optional fields you want to keep present in the payload rather than omitting. Before I write more than a one-line schema I usually paste a sample payload into a JSON formatter to see the actual shape pretty-printed. Type errors almost always come from misreading the structure.

Objects, required, and the additionalProperties trap

Most real validation work happens on objects. The three keywords you use every day are properties, required, and additionalProperties:

{
  "type": "object",
  "properties": {
    "email":    { "type": "string" },
    "age":      { "type": "integer" },
    "verified": { "type": "boolean" }
  },
  "required": ["email"],
  "additionalProperties": false
}

Enter fullscreen mode Exit fullscreen mode

Three gotchas to internalize. First, properties describes each field but does NOT make any of them required. Without the required array, every property is optional. Second, required is a separate list of property names that must be present (presence only, you still need type to validate the value). Third, additionalProperties: false rejects any property not listed. Without this line, the schema accepts arbitrary extra fields silently. This was the bug that hit me — the partner was sending email_address instead of email, and without additionalProperties: false my schema accepted it as "no email + an unknown field."

Set additionalProperties: false by default. Remove it only when you genuinely want a free-form object. For maps with arbitrary keys but a known value type, use it as a schema instead of a boolean:

{
  "type": "object",
  "additionalProperties": { "type": "number" }
}

Enter fullscreen mode Exit fullscreen mode

That validates any object where every value is a number. Perfect for price lookup tables, feature-flag percentages, or anything keyed dynamically.

String validation: minLength, pattern, format, enum

Real string validation goes beyond "is it a string." The keywords that earn their keep:

  • minLength / maxLength, integer bounds on UTF-16 code units (not bytes, not graphemes)
  • pattern, ECMA-262 regex the string must match somewhere (use ^...$ anchors for a full match)
  • format, named formats like email, uri, date, date-time, uuid, ipv4, ipv6
  • enum, a fixed list of allowed values (works for any type)
  • const, a single allowed value (equivalent to a one-item enum)

A practical username field:

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

Enter fullscreen mode Exit fullscreen mode

One gotcha that cost me a day: format is informational by default in older drafts. You must enable format assertion in your validator. Ajv requires ajv-formats. Python jsonschema needs format_checker. Without it, "format": "email" documents intent but does not actually reject invalid emails. See the JSON Schema spec for format for the full list and the assertion behavior per draft.

Number validation: minimum, maximum, multipleOf

For numbers and integers, the validation keywords are arithmetic:

  • minimum / maximum, inclusive bounds
  • exclusiveMinimum / exclusiveMaximum, exclusive bounds (in Draft 2020-12 these take a number, in older drafts they took a boolean)
  • multipleOf, the value must be a multiple of this number

Validating a percentage that must be 0 to 100 in 0.01 increments:

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

Enter fullscreen mode Exit fullscreen mode

multipleOf has a floating-point trap I keep getting wrong. 0.1 is not exactly representable in IEEE 754, so { "multipleOf": 0.1 } will sometimes reject values you expect to pass. For money, I now store and validate as integer cents ({ "type": "integer", "minimum": 0 }). It is the same precision argument behind storing prices in the smallest currency unit everywhere else in the stack.

Array validation: items, minItems, uniqueItems

For arrays the workhorses are items (schema applied to every element), minItems / maxItems (length bounds), and uniqueItems (rejects duplicates by deep equality). A list of unique tags:

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

Enter fullscreen mode Exit fullscreen mode

For positional tuples where each index has a different schema, use prefixItems in Draft 2020-12 or items as an array in older drafts. A coordinate pair where index 0 is longitude and index 1 is latitude:

{
  "type": "array",
  "prefixItems": [
    { "type": "number", "minimum": -180, "maximum": 180 },
    { "type": "number", "minimum":  -90, "maximum":  90 }
  ],
  "items": false
}

Enter fullscreen mode Exit fullscreen mode

The trailing "items": false rejects any extra elements beyond the two declared positions. The array equivalent of additionalProperties: false.

Schema composition: $ref, allOf, oneOf, anyOf

Once your schemas grow past a single page, you will want to break them up and combine them. JSON Schema has four composition keywords:

  • $ref, reuse another schema by JSON Pointer (e.g., "#/$defs/address" or an external URL)
  • allOf, data must validate against every subschema (intersection / mixin)
  • anyOf, data must validate against at least one (union, OK if multiple match)
  • oneOf, data must validate against exactly one (XOR, rejects if zero or multiple match)

A reusable address schema referenced from two parents:

{
  "$defs": {
    "address": {
      "type": "object",
      "properties": {
        "street":  { "type": "string" },
        "city":    { "type": "string" },
        "country": { "type": "string", "minLength": 2, "maxLength": 2 }
      },
      "required": ["street", "city", "country"]
    }
  },
  "type": "object",
  "properties": {
    "shipping": { "$ref": "#/$defs/address" },
    "billing":  { "$ref": "#/$defs/address" }
  }
}

Enter fullscreen mode Exit fullscreen mode

For discriminated unions (event types, message kinds), oneOf with a const discriminator is the standard pattern:

{
  "oneOf": [
    { "type": "object", "properties": { "kind": { "const": "email" },
        "to": { "type": "string", "format": "email" } }, "required": ["kind", "to"] },
    { "type": "object", "properties": { "kind": { "const": "sms" },
        "phone": { "type": "string", "pattern": "^\\+[1-9]\\d{1,14}$" } }, "required": ["kind", "phone"] }
  ]
}

Enter fullscreen mode Exit fullscreen mode

A real signup schema

Putting every keyword together, here is roughly the schema I now use for a signup endpoint:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "SignupRequest",
  "type": "object",
  "properties": {
    "email":     { "type": "string", "format": "email", "maxLength": 254 },
    "password":  { "type": "string", "minLength": 12, "maxLength": 128 },
    "username":  { "type": "string", "pattern": "^[a-zA-Z0-9_]{3,20}$" },
    "age":       { "type": "integer", "minimum": 13, "maximum": 120 },
    "country":   { "type": "string", "enum": ["US", "UK", "CA", "AU"] },
    "newsletter":{ "type": "boolean", "default": false },
    "referrals": { "type": "array", "items": { "type": "string", "format": "email" },
                   "maxItems": 5, "uniqueItems": true }
  },
  "required": ["email", "password", "username", "age", "country"],
  "additionalProperties": false
}

Enter fullscreen mode Exit fullscreen mode

It enforces the email format with the 254-char maximum from RFC 5321, a 12-character minimum password from NIST SP 800-63B, a regex-validated username, an integer age within plausible bounds, a closed enum of supported countries, an optional boolean with a documented default, and an optional referral list capped at 5 unique emails. The trailing additionalProperties: false is the line that would have saved me three days and 12,000 rows two years ago.

Tooling: Ajv (Node) and jsonschema (Python)

Declare which draft you target with the $schema keyword at the root. The two production-grade validators I reach for:

  • Ajv for Node.js and browser, the fastest JS validator, supports Draft 2020-12. Install ajv and ajv-formats together if you use format. Compile schemas once at startup with const validate = ajv.compile(schema), then call validate(data) on every request. This is 10 to 100 times faster than recompiling per call.
  • jsonschema for Python, the reference Python validator. Use Draft202012Validator(schema).validate(data) or iterate .iter_errors(data) to surface all errors at once instead of failing on the first.

For quick iteration without writing code, I usually paste the schema and a sample payload into a JSON formatter to confirm both parse, then run them through a browser-based validator. When debugging an unexpected failure, a diff checker helps me compare a failing payload against a known-good payload to spot the offending field.

JSON Schema vs OpenAPI vs TypeScript

These three describe data shapes but solve different problems:

  • TypeScript types are compile-time only. They vanish at runtime, so a malformed API payload will silently corrupt your program if you trust the type without validating. Great for developer ergonomics, useless for runtime safety.
  • JSON Schema is runtime validation that works in any language. Use it at API boundaries, for config files, for database documents, and for any cross-language data contract. A single schema can drive validation in your Node frontend, Python backend, and Go worker without rewriting.
  • OpenAPI (formerly Swagger) wraps JSON Schema inside an API description. It adds endpoints, methods, status codes, authentication, examples, and tooling for client SDK generation. Use it when you are describing an HTTP API and want documentation, client codegen, and validation in one document.

The stack I default to now: write the JSON Schema as source of truth, generate TypeScript types from it with json-schema-to-typescript, and embed the same schema inside an OpenAPI spec for HTTP routes. One source, three outputs, no drift.

The mistakes I kept making

1. Forgetting additionalProperties: false

The original bug. Without it, any extra field passes validation. A client typo like { "emial": "x@y.com" } validates as "no email present plus an unknown field" instead of the clean error you want. Add it by default.

2. Confusing required with type

Listing a property under properties does NOT make it required. You must also add it to the required array. Conversely, required only checks presence. A wrong-type field still fails, but on the type check, not the required check.

3. Using format without enabling assertion

In Ajv you must require('ajv-formats')(ajv). In Python jsonschema pass format_checker=FormatChecker(). Without this, format: email is metadata only and accepts any string. I burned half a day on this one.

4. oneOf where anyOf is correct

oneOf rejects data that matches more than one subschema. If your subschemas overlap (a value that is both a positive integer and a multiple of 5), oneOf rejects. Use it only for genuinely disjoint cases like discriminated unions.

5. multipleOf with floats

IEEE 754 cannot exactly represent 0.1. { "multipleOf": 0.1 } will reject values you expect to pass. Use integer units (cents, basis points) instead.

6. Recompiling schemas on every request

Ajv's compile() is expensive. The compiled validator is fast. Compile once at module load, store the function, reuse it.

Closing thought

JSON Schema looks verbose at first. Often the schema is longer than the data. That is the point. Every constraint you encode is one bug you cannot ship. Start with your top three API endpoints, then your config files, then your cross-service messages. Within a sprint you will catch at least one bug that would have made it to production.

If you want a sandbox, try the JSON Schema Reference Tutorial and an online validator like jsonschemavalidator.net. And if you ever debug a pattern validation that is misbehaving, a regex tester is faster than guessing.


Originally published at calculators.im.