How to Validate JSON: Complete Guide with Examples
JSON (JavaScript Object Notation) is the backbone of modern web APIs, configuration files, and data interchange. But invalid JSON can crash your application, break API integrations, and cause hours of debugging frustration. This guide walks you through everything you need to know about validating JSON, from basic syntax checks to advanced schema validation with real-world examples.
Why JSON Validation Matters
Invalid JSON is one of the most common sources of bugs in web
applications. A single misplaced comma, an unquoted key, or a trailing
comma can cause JSON.parse() to throw a
SyntaxError that crashes your entire data pipeline.
Validation catches these errors early, before they propagate through
your system and cause downstream failures.
Beyond syntax correctness, validation ensures that JSON data conforms to expected structures. An API might return valid JSON but with missing required fields, wrong data types, or values outside acceptable ranges. Schema validation addresses these structural concerns.
JSON Syntax Rules
Before diving into validation tools, it is essential to understand the rules that make JSON valid. JSON has a strict syntax defined by RFC 8259, and even a single character violation renders the entire document invalid.
Strings Must Use Double Quotes
All string values and object keys must be enclosed in double quotes. Single quotes are not valid JSON string delimiters, which is a common mistake for developers coming from JavaScript.
// Invalid - single quotes
{'name': 'Alice', 'age': 30}
// Valid - double quotes
{"name": "Alice", "age": 30}
Object Keys Must Be Quoted
Unlike JavaScript object literals, JSON requires all object keys to be enclosed in double quotes. Unquoted keys are a syntax error.
// Invalid - unquoted keys
{name: "Alice", age: 30}
// Valid - quoted keys
{"name": "Alice", "age": 30}
No Trailing Commas
JSON does not allow a comma after the last item in an object or array. This is another common mistake, especially when editing JSON by hand.
// Invalid - trailing comma
{
"name": "Alice",
"age": 30,
}
// Valid - no trailing comma
{
"name": "Alice",
"age": 30
}
No Comments
JSON does not support comments. Neither // single-line
comments nor /* */ multi-line comments are valid in JSON.
If you need documentation, use a separate file or a format like JSONC.
Common JSON Validation Errors
Understanding the most frequent errors helps you spot and fix them quickly. Here are the errors you will encounter most often:
- Unexpected token: Usually caused by single quotes, unquoted keys, or trailing commas. The error message includes the position where parsing failed.
- Unexpected end of JSON input: The JSON string is incomplete or empty. This often happens when a network request returns an empty response.
- Unexpected non-whitespace character: Extra content after the main JSON value, such as a second object not wrapped in an array.
-
Invalid number: Numbers with leading zeros (except
0 itself), hexadecimal notation, or
NaN/Infinityvalues are not valid JSON.
Validating JSON in JavaScript
The simplest way to validate JSON in JavaScript is to wrap
JSON.parse() in a try-catch block. If the JSON is
invalid, the method throws a SyntaxError.
function validateJSON(jsonString) {
try {
JSON.parse(jsonString);
return { valid: true };
} catch (error) {
return {
valid: false,
error: error.message
};
}
}
const result = validateJSON('{"name": "Alice"}');
console.log(result);
// { valid: true }
const badResult = validateJSON("{'name': 'Alice'}");
console.log(badResult);
// { valid: false, error: "Unexpected token '..." }
Validating JSON in Python
Python provides the json module with
json.loads() for parsing JSON strings. Similar to
JavaScript, invalid JSON raises a
json.JSONDecodeError with detailed position information.
import json
def validate_json(json_string):
try:
json.loads(json_string)
return {"valid": True}
except json.JSONDecodeError as e:
return {
"valid": False,
"error": str(e),
"line": e.lineno,
"column": e.colno
}
result = validate_json('{"name": "Alice"}')
print(result)
# {'valid': True}
JSON Schema Validation
Syntax validation only tells you if JSON is well-formed. JSON Schema lets you define the expected structure and validate data against it. A schema specifies required fields, data types, value ranges, string patterns, and nested object structures.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["name", "email"],
"properties": {
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0 }
}
}
Popular JSON Schema validators include Ajv for JavaScript, jsonschema for Python, and json-schema-validator for Java. These libraries validate JSON data against your schema and produce detailed error messages for each violation.
Online JSON Validation Tools
When you need to quickly check a JSON document without writing code, online validators are the fastest option. They provide instant feedback with error highlighting and line numbers.
Best Practices for JSON Validation
- Validate early: Check JSON at the boundary of your system, such as API endpoints and file import functions, before data enters your business logic.
- Use schema validation: Beyond syntax, validate data structure with JSON Schema to catch missing fields, wrong types, and out-of-range values.
- Provide clear error messages: When validation fails, include the field path, expected type, and actual value to help users fix the problem quickly.
- Validate on both client and server: Client-side validation provides immediate feedback, while server-side validation ensures security and data integrity.
-
Automate validation in CI/CD: Use tools like
ajv-cliorjsonschemato validate JSON fixtures and configuration files in your build pipeline. - Log validation errors: Record validation failures with context to identify patterns and fix root causes in data producers.
Ready to validate your JSON data? Try our free online JSON Validator with instant error detection and detailed feedback.
Validate JSON NowFrequently Asked Questions
What is JSON validation?
JSON validation is the process of checking whether a JSON document conforms to the correct syntax rules and optionally to a defined schema. Syntax validation ensures the JSON is well-formed, while schema validation ensures the data structure matches expected types, required fields, and value constraints.
What are the most common JSON errors?
The most common JSON errors are: trailing commas after the last item, single quotes instead of double quotes, unquoted object keys, comments (not allowed in JSON), and undefined or NaN values. These errors cause JSON.parse() to throw a SyntaxError.
How do I validate JSON in JavaScript?
Use JSON.parse() wrapped in a try-catch block. If the JSON is invalid, JSON.parse() throws a SyntaxError that you can catch and handle. For schema validation, use libraries like Ajv that implement JSON Schema validation.
What is JSON Schema?
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It defines the expected structure, types, required fields, value ranges, string patterns, and nested object structures. You can use it to validate that JSON data matches a specific format beyond basic syntax correctness.
Can I validate JSON online?
Yes, online JSON validators like the ToolHub JSON Validator let you paste JSON data and instantly see whether it is valid, with detailed error messages showing the exact line and column where errors occur.