How to Validate JSON: A Complete Developer's Guide (with Examples & Tools)
JSON (JavaScript Object Notation) is the backbone of modern data exchange — powering REST APIs, configuration files, databases, and data pipelines worldwide. But a single misplaced comma or unescaped character can bring an entire system to its knees. In this guide, you will learn how to validate JSON using online tools, JavaScript, Python, Node.js, and JSON Schema — with real-world examples, common error fixes, and best practices every developer should know.
1. Why JSON Validation Matters
Invalid JSON does not fail gracefully — it crashes parsers, throws uncaught exceptions, and silently corrupts data pipelines. Consider these real-world scenarios where JSON validation becomes critical:
- REST APIs: A backend returns a payload with a trailing comma. The mobile app's JSON parser throws an exception, and users see a blank screen.
- Configuration files: A DevOps engineer edits a
appsettings.jsonwith single-quoted strings. The application refuses to start. - Data pipelines: An ETL job ingests millions of records. One malformed JSON blob causes the entire batch to fail, requiring a full re-run.
- Webhooks & integrations: A third-party service sends an unexpected JSON structure. Without schema validation, your handler silently processes wrong data.
- Database storage: PostgreSQL and MongoDB both parse JSON at insert time. Bad JSON means failed writes and lost transactions.
Validating JSON at every boundary — ingestion, transformation, and output — is not optional for production systems. It is a core defensive programming practice. The earlier you catch a JSON syntax error, the cheaper it is to fix.
2. What Makes JSON Invalid? 6 Common Errors
The JSON specification (RFC 8259) is surprisingly strict. Here are the most common causes of invalid JSON, each with a broken example and the correct fix.
2.1 Trailing Commas
JavaScript developers often leave a trailing comma after the last property or array element. JSON does not allow this — it is a syntax error in every compliant parser.
// ❌ Invalid — trailing comma after last property
{
"name": "Alice",
"age": 30,
}
// ✅ Valid — no trailing comma
{
"name": "Alice",
"age": 30
}2.2 Single Quotes Instead of Double Quotes
JSON requires double quotes for all string keys and values. Single quotes are not valid JSON, even though JavaScript itself accepts them in object literals.
// ❌ Invalid — single-quoted keys and values
{
'city': 'New York',
'country': 'USA'
}
// ✅ Valid — double-quoted strings
{
"city": "New York",
"country": "USA"
}2.3 Missing Quotes Around Keys
In JavaScript object literals you can use unquoted keys. In JSON, every key must be wrapped in double quotes — no exceptions.
// ❌ Invalid — unquoted key
{
name: "Bob",
age: 25
}
// ✅ Valid — all keys quoted
{
"name": "Bob",
"age": 25
}2.4 Unescaped Special Characters in Strings
Certain characters inside JSON strings must be escaped with a backslash: \", \\, \/, \n, \t, \r, and Unicode escapes like \uXXXX.
// ❌ Invalid — literal tab and unescaped quote inside string
{
"message": "Hello World",
"note": "He said "hi""
}
// ✅ Valid — escaped characters
{
"message": "Hello World",
"note": "He said \"hi\""
}2.5 Comments in JSON
JSON does not support comments. Neither // line comments nor /* block comments */ are permitted. This surprises developers coming from JavaScript or JSON5.
// ❌ Invalid — comments are not allowed
{
// This is the user config
"theme": "dark", /* system default */
"lang": "en"
}
// ✅ Valid — remove all comments
{
"theme": "dark",
"lang": "en"
}2.6 Wrong Value Types
JSON supports only six value types: string, number, object, array, boolean (true/false), and null. Values like undefined, NaN, Infinity, and functions are not valid.
// ❌ Invalid — undefined and NaN are not JSON values
{
"score": NaN,
"result": undefined
}
// ✅ Valid — use null for missing values; avoid NaN
{
"score": null,
"result": null
}3. How to Validate JSON Online (Fastest Method)
The quickest way to check whether a JSON string is valid is to paste it into an online JSON validator. These tools parse your JSON instantly and highlight exactly where any syntax error occurs — no setup, no installation required.
JSONifyTools JSON Viewer & Validator is a free, browser-based tool that lets you:
- Paste raw JSON and instantly see if it is valid or not.
- View pretty-printed, syntax-highlighted output in a collapsible tree.
- See the exact line and column number of any syntax error.
- Copy or download the formatted JSON.
- Work entirely client-side — your data never leaves your browser.
For quick ad-hoc checks — debugging an API response, verifying a config file, or inspecting a webhook payload — an online JSON lint tool is by far the most efficient approach. Bookmark it alongside your developer tools.
4. How to Validate JSON in JavaScript
In the browser or any JavaScript runtime, JSON.parse() is the built-in JSON parser. Wrapping it in a try/catch block gives you immediate feedback on whether input is valid JSON.
Basic try/catch Pattern
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
console.log(isValidJSON('{"name":"Alice","age":30}')); // true
console.log(isValidJSON('{"name":"Alice","age":30,}')); // false — trailing comma
console.log(isValidJSON("{'name':'Alice'}")); // false — single quotesCustom Validator with Error Details
For better developer experience, return the parsed object on success and the error message on failure:
function validateJSON(str) {
try {
const parsed = JSON.parse(str);
return { valid: true, data: parsed, error: null };
} catch (err) {
return { valid: false, data: null, error: err.message };
}
}
const result = validateJSON('{"user": "Bob", "active": true}');
if (result.valid) {
console.log("Parsed data:", result.data);
} else {
console.error("JSON Error:", result.error);
// e.g. "JSON Error: Unexpected token } in JSON at position 30"
}Note that JSON.parse validates syntax only — it does not check whether the data matches your expected structure. For structural validation, you need JSON Schema (covered in Section 7).
5. How to Validate JSON in Python
Python's standard library includes the json module, which provides json.loads() for parsing JSON strings and json.load() for reading from file objects. Both raise json.JSONDecodeError on invalid input.
Validating a JSON String
import json
def is_valid_json(text: str) -> bool:
try:
json.loads(text)
return True
except json.JSONDecodeError:
return False
print(is_valid_json('{"name": "Alice", "age": 30}')) # True
print(is_valid_json('{"name": "Alice", "age": 30,}')) # FalseCapturing Detailed Error Information
import json
def validate_json(text: str):
try:
data = json.loads(text)
return {"valid": True, "data": data, "error": None}
except json.JSONDecodeError as e:
return {
"valid": False,
"data": None,
"error": {
"message": e.msg,
"line": e.lineno,
"column": e.colno,
"position": e.pos,
},
}
result = validate_json('{"city": "Paris" "country": "France"}')
print(result)
# {
# 'valid': False,
# 'data': None,
# 'error': {'message': 'Expecting , delimiter', 'line': 1, 'column': 18, 'position': 17}
# }Validating a JSON File in Python
import json
def validate_json_file(filepath: str) -> bool:
try:
with open(filepath, "r", encoding="utf-8") as f:
json.load(f)
print(f"✅ {filepath} is valid JSON")
return True
except json.JSONDecodeError as e:
print(f"❌ {filepath} is invalid JSON: {e}")
return False
except FileNotFoundError:
print(f"❌ File not found: {filepath}")
return False
validate_json_file("config.json")6. Validate JSON in Node.js (with AJV Schema Validation)
In Node.js you can validate JSON files from disk and also perform JSON Schema validation using AJV (Another JSON Validator), the most popular and performant JSON Schema library in the JavaScript ecosystem.
Reading and Validating a JSON File
const fs = require("fs");
function validateJSONFile(filePath) {
try {
const raw = fs.readFileSync(filePath, "utf-8");
const parsed = JSON.parse(raw);
console.log("✅ Valid JSON:", parsed);
return parsed;
} catch (err) {
if (err instanceof SyntaxError) {
console.error("❌ JSON Syntax Error:", err.message);
} else {
console.error("❌ File Error:", err.message);
}
return null;
}
}
validateJSONFile("./data.json");Schema Validation with AJV
// npm install ajv
const Ajv = require("ajv");
const ajv = new Ajv({ allErrors: true });
const schema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer", minimum: 0 },
email: { type: "string", format: "email" },
},
required: ["name", "age", "email"],
additionalProperties: false,
};
const validate = ajv.compile(schema);
const data = { name: "Alice", age: 30, email: "alice@example.com" };
if (validate(data)) {
console.log("✅ Data is valid");
} else {
console.error("❌ Validation errors:", validate.errors);
// [{ instancePath: '/age', message: 'must be integer' }, ...]
}7. What Is JSON Schema?
JSON Schema is a vocabulary for annotating and validating JSON documents. While JSON.parse only checks syntax, JSON Schema lets you enforce the structure, types, and constraints of your data — ensuring that a user object always has a name string, an age integer, and a valid email field.
JSON Schema is defined in its own JSON document and includes key keywords:
$schema— URI identifying the JSON Schema version (e.g.,https://json-schema.org/draft/2020-12/schema).type— the data type:string,number,integer,boolean,object,array,null.properties— an object defining the schema for each key in a JSON object.required— an array of property names that must be present.minimum/maximum— numeric range constraints.minLength/maxLength— string length constraints.enum— restricts a value to a fixed set of options.additionalProperties— whether to allow keys not listed inproperties.
JSON Schema is the industry standard for API contract validation, form data validation, and CI/CD config checks. It is supported in virtually every programming language.
8. Writing Your First JSON Schema
Let's build a real schema for a user registration payload. The user object must have a name, email, age, and optional role.
The JSON Data
{
"name": "Alice Johnson",
"email": "alice@example.com",
"age": 28,
"role": "admin"
}The JSON Schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/schemas/user.json",
"title": "User",
"description": "A registered user of the application",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100,
"description": "Full name of the user"
},
"email": {
"type": "string",
"format": "email",
"description": "Valid email address"
},
"age": {
"type": "integer",
"minimum": 13,
"maximum": 120,
"description": "Age of the user (must be at least 13)"
},
"role": {
"type": "string",
"enum": ["user", "admin", "moderator"],
"default": "user",
"description": "User's permission role"
}
},
"required": ["name", "email", "age"],
"additionalProperties": false
}This schema enforces that name, email, and age are always present, that age is an integer between 13 and 120, that role is one of three allowed values, and that no unexpected fields are allowed.
9. JSON Schema Validators: Tool Comparison
Once you have a schema, you need a JSON Schema validator library to run validation in your application. Here is a comparison of the most widely used options:
| Library | Language | Draft Support | Performance | Notes |
|---|---|---|---|---|
| AJV | JavaScript / Node.js | Draft-07, 2019-09, 2020-12 | ⚡ Fastest (JIT compiled) | Most popular; 100M+ weekly downloads |
| jsonschema | Python | Draft-03 through 2020-12 | Moderate | Standard Python choice; extensive docs |
| Zod | TypeScript / JS | TypeScript-native (not JSON Schema) | Fast | TypeScript-first; schema infers TS types |
| tv4 | JavaScript | Draft-04 | Moderate | Older; still widely used in legacy apps |
| jsonschema (Go) | Go | Draft-07, 2019-09 | Fast | Popular in Go microservices |
| Newtonsoft.Json | C# / .NET | Draft-04, Draft-06 | Fast | De facto standard in .NET ecosystem |
Recommendation: Use AJV for Node.js/TypeScript projects, jsonschema for Python, and Zod when you want TypeScript type inference tightly coupled to your runtime validation.
10. Common JSON Validation Errors & How to Fix Them
Here is a quick-reference table of the most common JSON errors you will encounter, their root causes, and the exact fix:
| Error Message | Cause | Fix |
|---|---|---|
Unexpected token } | Trailing comma before closing brace | Remove the trailing comma |
Unexpected token ' | Single-quoted string | Replace all single quotes with double quotes |
Unexpected token u | Value is undefined (not valid JSON) | Replace undefined with null |
Unexpected non-whitespace character | Missing comma between properties | Add the missing comma |
Unexpected end of JSON input | Truncated / incomplete JSON string | Check network response or file for truncation |
Expected property name or '}' | Unquoted key or extra comma | Add double quotes around the key |
Invalid escape character | Backslash before non-escape character (e.g. \p) | Use valid escape sequences or double the backslash |
Circular structure to JSON | Object contains a circular reference | Use a replacer function in JSON.stringify or a library like flatted |
must have required property 'X' (AJV) | JSON Schema required field missing | Add the required field to your JSON payload |
must be integer (AJV) | Number is a float but schema requires integer | Send 30 instead of 30.0 |
11. Frequently Asked Questions (FAQ)
What is the difference between "valid JSON" and "correct JSON"?
Valid JSON means the text conforms to the JSON syntax specification (RFC 8259) — parsers can read it without throwing a syntax error. Correct JSON (or semantically valid JSON) means the data also matches the expected structure and constraints for your application — for example, an age field must be a non-negative integer, not an arbitrary string. You need JSON Schema validation to enforce correctness beyond syntax.
Can JSON have comments?
No. The official JSON specification does not allow comments of any kind — no // line comments and no /* block comments */. This was an intentional design decision by Douglas Crockford (JSON's creator) to keep JSON a data-interchange format rather than a configuration language. If you need comments in config files, consider JSON5, JSONC (JSON with Comments, used by VS Code), or TOML / YAML as alternatives.
Is null a valid JSON value?
Yes. null is one of the six primitive types in JSON (string, number, boolean, null, object, array). A JSON document consisting solely of null is perfectly valid. You can also use null as a property value to represent the intentional absence of a value — far better than omitting the field entirely or using the string "null". Note that undefined, NaN, and Infinity are not valid JSON values.
What tool validates JSON for free?
There are several free options for JSON validation online: JSONifyTools JSON Viewer provides instant syntax validation, pretty-printing, and a collapsible tree view — all free, with no sign-up required and no data sent to a server. For programmatic validation in your app, AJV (JavaScript) and jsonschema (Python) are both open-source and completely free. For CI/CD pipelines, you can use the command-line tool python -m json.tool file.json or jq . file.json to validate JSON files without any additional dependencies.
12. Conclusion
JSON validation is a multi-layered discipline. At the most basic level, syntax validation ensures that your JSON can be parsed at all — catching issues like trailing commas, single quotes, and missing brackets. At the next level, schema validation with JSON Schema ensures that your data has the right structure, types, and constraints — the difference between merely parseable JSON and JSON that is correct and safe to use.
Here is a summary of the best validation strategy at each layer of your stack:
- During development: Use an online JSON validator tool like JSONifyTools for instant feedback.
- In JavaScript / Node.js: Use
JSON.parsein atry/catchfor syntax, and AJV for schema validation. - In Python: Use
json.loadsfor syntax and thejsonschemapackage for structural validation. - In TypeScript: Consider Zod for type-safe validation that gives you both runtime validation and compile-time type inference in one library.
- In CI/CD pipelines: Use
jqorpython -m json.toolto validate JSON files during build and deployment steps. - At API boundaries: Always validate incoming JSON against a schema before processing it — never trust that clients will send well-formed data.
By applying these techniques, you will spend far less time debugging mysterious runtime errors caused by malformed data and far more time building features that matter.
Ready to validate your JSON right now?
Use our free JSON Viewer & Validator to instantly check any JSON for syntax errors, view it in a collapsible tree, and pretty-print it — no sign-up required, 100% client-side.