How to Validate JSON: A Comprehensive Step-by-Step Tutorial
Learn how to validate JSON, common errors to look for, and practical examples from real-world development.
What is JSON validation, and why should you care?
JSON validation is the process of checking whether a string conforms to the JSON specification (RFC 8259). A validator either confirms your JSON is valid or gives you a precise error message pointing to exactly where the problem is.
Let me tell you a war story from early in my career. I once spent 3 hours debugging an API integration that was failing with a vague 'Bad Request' error. The JSON I was sending looked fine to my eyes — I had even read it through twice. Eventually, I ran it through a validator and discovered I had a single trailing comma on line 47. Three hours lost over one comma. Ever since then, validating JSON has been my first step when something doesn't work.
Validation matters because JSON parsers are strict. What looks 'close enough' to you is an outright error to a parser. And while some parsers are lenient and accept slightly invalid JSON, you should never rely on that behavior — it will come back to bite you when you least expect it.
Validation is also important because it's fast. Catching an error early saves you from chasing down bugs in your code when the problem was just malformed data the whole time.
The 7 most common JSON validation errors (and how to fix them)
These 7 errors account for roughly 95% of all JSON validation failures I've seen. Learn to spot them, and you'll fix most issues in seconds:
**1. Trailing commas** — The #1 culprit. JSON does not allow a comma after the last item in an object or array. This is totally fine in JavaScript, but invalid in JSON.
Invalid:
{
"name": "John",
"age": 30, // This comma is invalid!
"active": true,
} Fixed:
{
"name": "John",
"age": 30,
"active": true
} **2. Single quotes instead of double quotes** — All keys and string values must use double quotes, not single quotes.
Invalid:
{
'name': 'John',
'email': '[email protected]'
} Fixed:
{
"name": "John",
"email": "[email protected]"
} **3. Unquoted object keys** — Every key in a JSON object must be quoted, even if they're valid JavaScript identifiers.
Invalid:
{
name: "John",
age: 30
} Fixed:
{
"name": "John",
"age": 30
} **4. Missing quotes around string values** — String values need quotes too. Numbers, booleans, and null don't, but strings always do.
Invalid:
{
"name": John,
"status": active
} Fixed:
{
"name": "John",
"status": "active"
} **5. Invalid escape sequences** — Certain characters need escaping when they appear inside strings. Backslashes, quotes, and control characters (newlines, tabs) are the usual suspects.
Invalid:
{
"path": "C:\Users\John",
"message": "He said "Hello""
} Fixed:
{
"path": "C:\\Users\\John",
"message": "He said \"Hello\""
} **6. Comments** — JSON does not support comments. Not `//` line comments, not `/* */` block comments. This was an explicit design decision by Douglas Crockford to prevent using JSON as a config format with comments (though people do it anyway with JSON5 or YAML).
Invalid:
{
"name": "John", // User name
"age": 30 /* User age */
} Fixed:
{
"name": "John",
"age": 30
} **7. Undefined or non-JSON values** — You can't have `undefined`, functions, Date objects, RegExp objects, or other JavaScript-specific values in JSON. Only objects, arrays, strings, numbers, booleans, and `null` are allowed.
Invalid:
{
"name": "John",
"createdAt": new Date(),
"deleted": undefined
} Fixed (using ISO string for date and omitting undefined or using null):
{
"name": "John",
"createdAt": "2026-06-20T14:30:00Z",
"deleted": null
} If validation fails, check for these 7 issues first — you'll usually find your answer quickly.
How to validate JSON: A practical walkthrough
Let's work through a realistic example. Imagine you're writing a config file for a new feature, and you've come up with this JSON:
{
feature: "search-enhancements",
enabled: true,
options: {
algorithms: ['semantic', 'keyword', 'hybrid'],
defaultLimit: 50,
maxLimit: 100,
highlighting: true,
},
environments: {
development: true,
staging: true,
production: false
}
} Looks reasonable, right? Let's validate it and see what happens. The validator will fail on the first unquoted key `feature`. Let's fix that, then check again. Now we've got more unquoted keys — `enabled`, `options`, `algorithms`, etc. Let's quote all the keys.
Next up: single quotes around `['semantic', 'keyword', 'hybrid']` — need to change those to double quotes. Then we've got a trailing comma after `highlighting: true,`. Let's fix all that:
{
"feature": "search-enhancements",
"enabled": true,
"options": {
"algorithms": ["semantic", "keyword", "hybrid"],
"defaultLimit": 50,
"maxLimit": 100,
"highlighting": true
},
"environments": {
"development": true,
"staging": true,
"production": false
}
} Now this validates! Notice how we fixed multiple issues along the way. The key workflow is: validate, fix the first error, validate again, repeat until it passes. Validators usually only report the first error they encounter, so you need to iterate.
Always validate before you format, convert, or use JSON in your code. Catching errors early saves you from confusing bugs later. I can't tell you how many times I've seen someone try to debug why their code can't parse some JSON, only to discover the JSON was never valid to begin with.
JavaScript vs JSON: Know the critical differences
JSON is a subset of JavaScript object literal syntax, but not everything that's valid JavaScript is valid JSON. This is a common source of confusion for developers — I still see experienced devs mix these up occasionally.
Here's what's valid in JavaScript but invalid in JSON:
- **Single quotes**: `{'name': 'John'}` works in JS, not in JSON
- **Unquoted keys**: `{name: 'John'}` works in JS, not in JSON
- **Trailing commas**: `{a: 1,}` works in JS (especially ES5+), not in JSON
- **Comments**: `{/* comment */}` works in JS, not in JSON
- **`undefined` values**: `{a: undefined}` works in JS, not in JSON — use `null` instead
- **Functions**: `{fn: function() {}}` works in JS, not in JSON
- **Objects with constructors**: `{date: new Date()}` works in JS, not in JSON — use ISO strings instead
- **Regular expressions**: `{pattern: /test/}` works in JS, not in JSON
- **Octal and hex numbers**: `0777` or `0xFF` work in JS, not in JSON
- **Multi-line strings**: Template literals with backticks work in JS, not in JSON
If you're copying something from a JavaScript file into JSON, you'll almost certainly need to make changes. The safest way is to use `JSON.stringify()` in JavaScript to generate valid JSON from a JavaScript object — that way you know it's correct.
Here's an example of converting a JS object to JSON properly:
const config = {
feature: 'search-enhancements',
enabled: true,
options: {
algorithms: ['semantic', 'keyword', 'hybrid'],
defaultLimit: 50,
maxLimit: 100,
highlighting: true
}
};
// This gives you valid JSON
const json = JSON.stringify(config, null, 2);
console.log(json); Using `JSON.stringify()` ensures you get valid JSON every time. I use this trick constantly when I need to create JSON from scratch — I write it as a JavaScript object first, then stringify it.
Beyond syntax: Schema validation for production APIs
Syntax validation (what we've been talking about) is essential, but for production APIs, you usually need something more: schema validation. Schema validation checks not just that the JSON is syntactically valid, but that it has the right shape — the right fields, the right data types, the right structure.
There are several schema languages you can use:
- **JSON Schema**: The most widely adopted standard. Rich ecosystem, good tooling.
- **TypeScript**: If you're in a TypeScript project, you can use types to validate at compile time (though you still need runtime validation).
- **Zod**: A fantastic TypeScript-first schema validation library that gives you both static types and runtime validation.
- **Joi**: Popular in the Node.js ecosystem, especially with Express and Hapi.
- **Valibot**: A smaller, faster alternative to Zod.
Here's a quick example with Zod, my current favorite:
import { z } from 'zod';
const UserSchema = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
email: z.string().email(),
createdAt: z.string().datetime(),
active: z.boolean()
});
// Validate JSON data
const result = UserSchema.safeParse(jsonData);
if (result.success) {
// Data is valid, and TypeScript knows the type
console.log(result.data);
} else {
// Detailed error messages
console.error(result.error);
} For APIs, always validate both the syntax and the schema. Never trust incoming JSON to be the right shape — validate it explicitly. This prevents a whole class of bugs from bad data making it into your system.
Tools and workflows for validating JSON
Here are the tools I actually use for validating JSON in my daily work:
**Online validators**: Quick and convenient for one-off tasks. Look for ones that show you the exact error location with a pointer to the line and column.
**Code editor extensions**: VS Code has excellent built-in JSON validation — it will underline errors in red as you type and show you the error message when you hover. Sublime Text and WebStorm have similar features.
**Command-line tools**: `jq` will tell you if JSON is invalid. You can also use Python's built-in json module:
# With Python
python3 -m json.tool data.json > /dev/null
# With jq
jq . data.json > /dev/null **Pre-commit hooks**: You can set up pre-commit hooks with tools like Prettier and eslint-plugin-json to validate JSON files automatically before they're committed to git. This prevents invalid JSON from ever making it into your repo.
**CI checks**: Run JSON validation as part of your CI pipeline. This catches invalid JSON even if someone bypasses the pre-commit hooks.
My personal workflow is: write JSON in VS Code (which validates as I type), use an online validator if I'm debugging something tricky, and have pre-commit hooks and CI checks to catch anything that slips through. It's simple, but effective.
Try These Tools
Open the tools that go with this tutorial and practice what you learned.
More Tutorials in This Category
Learn how to format JSON for readability, common use cases, and step-by-step examples with real-world scenarios.
Learn how to compare JSON files, spot differences, and understand what changed with real-world debugging workflows.
Keep Learning
How to Format JSON: A Practical Developer Guide
Learn how to format JSON for readability, common use cases, and step-by-step examples with real-world scenarios.
How to Compare Two JSON Documents Effectively
Learn how to compare JSON files, spot differences, and understand what changed with real-world debugging workflows.