How to Validate JSON: Syntax Diagnostics, JSON Schema (Draft 2020-12), and Runtime Validation
Learn how to validate JSON data: debugging syntax errors, defining JSON Schema (Draft 2020-12) contracts, and validating runtime payloads with Ajv, Zod, and Pydantic.
The Two Levels of JSON Validation
Validating JSON requires verifying two distinct layers of correctness: Syntactic Conformance (verifying that the string conforms to RFC 8259 grammar rules) and Semantic/Schema Conformance (verifying that the parsed data structure matches expected keys, types, ranges, and invariants).
Common Syntax Errors & Exact Fixes
| Syntax Error | Invalid Example | Fixed Example | RFC 8259 Rule |
|---|---|---|---|
| Trailing Commas | `{"a": 1, "b": 2,}` | `{"a": 1, "b": 2}` | Trailing commas are strictly prohibited after the last element. |
| Single Quotes | {'name': 'Alex'} | {"name": "Alex"} | All keys and string values must use double quotes (`"`). |
| Unquoted Keys | `{name: "Alex"}` | `{"name": "Alex"}` | Keys must always be valid double-quoted strings. |
| Unescaped Control Characters | `{"text": "Line 1 \n Line 2"}` (literal newline) | `{"text": "Line 1\nLine 2"}` | Newlines, tabs, and backslashes must be escaped (`\n`, `\t`, `\\`). |
| Comments | `{"a": 1 /* note */}` | `{"a": 1}` | Standard JSON does not support inline or block comments. |
Structural Validation with JSON Schema (Draft 2020-12)
JSON Schema provides an industry-standard declarative language to enforce data structure contracts across APIs and microservices:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UserRegistration",
"type": "object",
"properties": {
"userId": { "type": "string", "format": "uuid" },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 18 },
"roles": {
"type": "array",
"items": { "type": "string", "enum": ["viewer", "editor", "admin"] },
"minItems": 1
}
},
"required": ["userId", "email", "roles"],
"additionalProperties": false
}Runtime Type Validation: Zod & Pydantic
In TypeScript and Python backends, developers use runtime schema parsers that validate JSON payloads and infer static types simultaneously:
import { z } from 'zod';
const UserSchema = z.object({
userId: z.string().uuid(),
email: z.string().email(),
age: z.number().int().min(18),
roles: z.array(z.enum(['viewer', 'editor', 'admin'])).min(1)
});
// Infer static TypeScript type directly from schema
export type User = z.infer<typeof UserSchema>;
export function validateUserInput(data: unknown): User {
return UserSchema.parse(data); // Throws structured ZodError on mismatch
}High-Performance Schema Validation with Ajv
While Zod is ideal for client-side forms and API boundaries in TypeScript, Ajv (Another JSON Schema Validator) compiles JSON Schema into highly optimized JIT JavaScript functions, achieving over 1,000,000 validations per second on server backends:
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
const ajv = new Ajv({ allErrors: true });
addFormats(ajv);
const validate = ajv.compile({
type: 'object',
properties: {
name: { type: 'string', minLength: 2 },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email']
});
const data = { name: 'Alex', email: 'alex@cosharex.com' };
const valid = validate(data);
if (!valid) {
console.error('Validation errors:', validate.errors);
}Code Formatter & Converter Suite
Validate, format, minify, and convert JSON, SQL, YAML, XML, and code dialects directly on your local machine.
Frequently Asked Questions
How do I locate the exact line number of a JSON syntax error in JavaScript?
Native `JSON.parse()` error messages in modern V8 engines report the exact character position (e.g. `Unexpected token at position 142`). You can calculate the line and column by splitting the preceding text substring by newlines.
What is JSONC vs standard JSON?
JSONC (JSON with Comments) is a non-standard superset used by VS Code (`tsconfig.json`, `settings.json`) that allows single-line (`//`) and block (`/* */`) comments. It must be stripped before passing to standard `JSON.parse()`.
Conclusion
For large JSON payloads, mismatched braces or brackets can be tough to debug. A good JSON validator parses your structure step-by-step and points you directly to the offending line number. When debugging, look for missing commas or unclosed arrays within large nested objects.
Related Articles
Streaming & Parsing Large JSON Files Without Crashing Memory: Node.js, Python & Web Workers
Master streaming and parsing multi-gigabyte JSON datasets: SAX/event-driven tokenizers, stream-json in Node.js, ijson in Python, and 64-bit precision preservation.
Developer ToolsJSON Minification: Performance Gains, Gzip Interaction, and Streaming Parsers
Understand how JSON minification reduces bandwidth and compute costs, how minification interacts with gzip/Brotli compression, and how to stream minify large payloads.
Developer ToolsJSON vs XML: Structural Architecture, Parsing Performance, and Modern Use Cases
A deep architectural comparison between JSON and XML: data types, schema validation (JSON Schema vs XSD), payload overhead, and parsing performance.