JSON validation is the first thing you should do whenever JSON leaves one system and enters another — before it hits your API, before it gets stored in a database, before it is processed by a script. Invalid JSON does not produce a helpful error; it produces a parse failure that is often attributed to the wrong component. This guide covers every practical method for validating JSON online and offline, explains what "valid JSON" actually means, and shows you how to diagnose and fix the most common errors.
What does 'valid JSON' actually mean?
JSON (JavaScript Object Notation) has a formal specification defined by RFC 8259 and the ECMA-404 standard. A JSON document is valid when it conforms to this specification completely — no more, no less. The rules are stricter than most people expect, and several things that JavaScript permits are explicitly disallowed in JSON.
The JSON specification rules
- Strings must use double quotes — single-quoted strings (`'value'`) are not valid JSON even though JavaScript accepts them.
- No trailing commas — `[1, 2, 3,]` and `{"a": 1,}` are invalid; the comma after the last element must be removed.
- No comments — `// line comments` and `/* block comments */` are not part of the JSON spec.
- No undefined values — `undefined` is a JavaScript concept; JSON only allows `null`, numbers, strings, booleans, arrays, and objects.
- Numbers cannot have leading zeros — `012` is not valid JSON; use `12` instead.
- Object keys must be strings — `{1: "value"}` is invalid; keys must be double-quoted strings.
- No control characters in strings — raw newlines, tabs, and other control characters must be escaped (`\n`, `\t`, etc.).
Note
Syntactically valid vs. semantically valid
A JSON document can be syntactically valid (correctly formed per the specification) but semantically invalid for your application. For example, a JSON object with "age" set to -5 is valid JSON but an invalid age for a user profile. Syntax validation is what a JSON parser checks; schema validation is what catches semantic errors. Both layers matter, and this guide covers both.
How to validate JSON online in seconds
The fastest way to check whether a JSON string is valid is to paste it into an online JSON validator. No install, no configuration, no account. The result is instant, and — when you use a browser-based tool — your data never leaves your device.
A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array.
Using the JSON Formatter and Validator
The JSON Formatter & Validator on Quasar Tools validates and formats JSON simultaneously. Paste any JSON string and it tells you immediately whether the input is valid. If it is invalid, the tool highlights the error position with a line number and a plain-language description of what went wrong. If it is valid, it outputs clean, indented JSON you can copy straight into your project.
This dual-purpose approach matters in practice. When you receive JSON from an API, copy it from a config file, or grab it from a log line, the raw text is often minified and hard to read. Formatting it as part of validation gives you two things at once: confirmation that the JSON is valid, and a readable version you can actually inspect.
Tip
JSON Formatter & Validator
Paste any JSON string to instantly validate, pretty-print, and syntax-highlight it in your browser — with line-level error diagnostics and no uploads.
Common JSON errors and how to fix them
Most invalid JSON documents fail for one of five reasons. Knowing these patterns lets you fix errors quickly without relying entirely on a tool to diagnose them.
Trailing comma
Trailing commas are the most common JSON error, largely because JavaScript and most modern languages permit them in object and array literals. JSON does not. Remove the comma after the last property in every object and the last element in every array.
// ❌ Invalid — trailing comma after last property
{
"name": "Alice",
"age": 30,
}
// ✓ Valid — no trailing comma
{
"name": "Alice",
"age": 30
}Single-quoted strings
Single quotes are valid in JavaScript but explicitly prohibited in JSON. Every string — both keys and values — must use double quotes. This error is common when JSON is hand-authored or copied from a JavaScript object literal.
// ❌ Invalid — single-quoted key and value
{'city': 'London'}
// ✓ Valid — double-quoted key and value
{"city": "London"}Comments in the JSON
JSON has no comment syntax. If your JSON contains `//` or `/* */` comments — often added to config files for documentation — a standard JSON parser will reject the entire document. Strip all comments before parsing, or switch to a format like JSONC or JSON5 that supports them natively.
// ❌ Invalid — comments are not part of the JSON spec
{
// This is the user object
"name": "Alice",
"role": "admin" /* elevated permissions */
}Unescaped special characters in strings
Raw newlines, tabs, backslashes, and certain Unicode control characters must be escaped inside JSON strings. A raw newline inside a string value — as opposed to the `\\n` escape sequence — makes the JSON unparseable. This error frequently appears when JSON is generated by concatenating strings in code rather than using a proper JSON serialiser.
// ❌ Invalid — raw newline inside string value
{"message": "line one
line two"}
// ✓ Valid — escaped newline
{"message": "line one\nline two"}Mismatched brackets or braces
An unclosed brace, bracket, or mismatched closing delimiter causes a parse failure. This is common in hand-edited JSON and in JSON generated by code that builds payloads through string concatenation. A formatter with bracket-matching makes these visible immediately.
// ❌ Invalid — array opened but object closed
{
"items": [1, 2, 3
}
// ✓ Valid — matching brackets
{
"items": [1, 2, 3]
}JSON Duplicate Key Detector
Detect repeated object keys in any JSON payload — silent overwrites from duplicate keys are valid per some parsers but cause data loss and hard-to-diagnose bugs.
JSON Schema validation: checking values, not just syntax
Syntax validation confirms the JSON is well-formed. Schema validation confirms the JSON contains the right data — the right fields, the right types, the right value ranges. These are two distinct checks, and both are needed in production systems.
What is JSON Schema?
JSON Schema is a vocabulary for describing the structure and constraints of a JSON document. A schema document specifies which fields are required, what type each field must be, minimum and maximum values for numbers, allowed string patterns, and more. When you validate a JSON document against a schema, you get precise errors like "field 'email' is required" or "field 'age' must be a positive integer" — not just "invalid JSON."
Using the JSON Schema Validator
The JSON Schema Validator on Quasar Tools accepts a JSON payload and a JSON Schema and validates the payload against the schema constraints. It reports rule-level errors with the exact field path that failed — so you know not just that validation failed, but which field violated which rule. This is the right tool when you need to verify that an API response matches a contract, or that a config file contains all required settings.
Note
Syntax validation vs. schema validation
| Aspect | Syntax Validation | Schema Validation |
|---|---|---|
| What it checks | JSON spec conformance | Data types, fields, constraints |
| Tool required | Any JSON parser | JSON Schema validator |
| Error output | Line/char position | Field path + rule violated |
| Catches | Missing quotes, bad commas | Wrong type, missing field |
| When to use | Always — first check | When a contract exists |
| Pass = guarantee | Parseable by any JSON library | Matches your data model |
Generating a schema from an existing payload
The fastest way to add schema validation to an existing project is to generate the schema from a known-good payload. Paste a representative JSON object into the JSON Schema Generator and it produces a complete schema with type definitions, required fields, and format hints. Copy the output into your project and use it as the validation contract for all future payloads of that type.
Validating JSON programmatically
Online tools are the fastest choice for one-off checks, but production systems need JSON validation embedded in code. Every major programming language has at least one well-maintained JSON parsing library, and most have dedicated schema validation libraries as well.
JavaScript and TypeScript
In JavaScript, `JSON.parse()` throws a `SyntaxError` when given invalid JSON — wrap it in a try/catch to handle the error gracefully. For schema validation, AJV (Another JSON Validator) is the most widely used library, supporting JSON Schema Draft-07 through Draft 2020-12 with high performance. Zod is a popular TypeScript-first alternative that validates JSON against runtime type schemas with full TypeScript inference. The JSON to Zod Schema converter on Quasar Tools generates a Zod schema from any JSON payload automatically.
function isValidJson(input: string): boolean {
try {
JSON.parse(input);
return true;
} catch {
return false;
}
}
// Or get the parsed value and the error together:
function parseJson<T>(input: string): { data: T } | { error: string } {
try {
return { data: JSON.parse(input) as T };
} catch (e) {
return { error: (e as SyntaxError).message };
}
}Python
Python's built-in `json` module raises `json.JSONDecodeError` (a subclass of `ValueError`) when parsing fails. The error object includes the line number, column, and a description. For schema validation, jsonschema and pydantic are the standard choices — pydantic is particularly popular in FastAPI projects because it validates and deserialises JSON into typed Python objects in a single step.
import json
def is_valid_json(text: str) -> bool:
try:
json.loads(text)
return True
except json.JSONDecodeError as e:
print(f"Invalid JSON at line {e.lineno}, col {e.colno}: {e.msg}")
return FalseCommand line
On any system with Python installed, `python3 -m json.tool input.json` validates and pretty-prints a JSON file in one command. The exit code is non-zero on failure, making it suitable for shell scripts and CI pipelines. The `jq` tool is a more powerful alternative: `jq . input.json` validates and formats, while `jq 'empty' input.json` validates without producing output.
# Validate and pretty-print with Python (built-in, no install)
python3 -m json.tool input.json
# Validate silently with jq (exit code 0 = valid, 1 = invalid)
jq empty input.json && echo "Valid" || echo "Invalid"
# Validate multiple files with a loop
for f in *.json; do
jq empty "$f" && echo "$f: valid" || echo "$f: INVALID"
doneTip
Validating special JSON formats
Standard JSON validation covers `.json` files and API payloads. But JSON appears in several other formats that have their own validation requirements — formats where a standard JSON parser either produces incorrect results or rejects the entire input.
JSONL and NDJSON (JSON Lines)
JSON Lines (`.jsonl`) files contain one JSON object per line with no enclosing array. This format is standard for log files, ML training datasets, and streaming APIs. A standard JSON parser rejects a JSONL file because the file as a whole is not a valid JSON document — each line must be parsed individually. The JSON Lines Validator & Fixer validates every line separately, reports which line numbers have errors, and offers safe auto-fixes for common formatting issues.
JSON with duplicate keys
The JSON specification technically permits duplicate keys in objects, but the behavior is undefined — different parsers handle it differently. Python's `json.loads()` keeps the last value; some parsers keep the first; others raise an error. In practice, duplicate keys are almost always a bug — either a merge gone wrong or a templating error. The JSON Duplicate Key Detector finds all repeated keys and tells you exactly where they occur.
JSON in YAML config files
YAML is a superset of JSON, so any valid JSON is also valid YAML. But JSON embedded in YAML files — as the value of a string field, for example — needs its own validation. If you are working with YAML configs that contain embedded JSON values, validate the JSON portions separately with the JSON formatter, then validate the overall YAML with a YAML validator. If your project uses both formats and you need to compare two config files, the JSON/YAML Diff Highlighter handles both simultaneously.
Warning
JSON validation best practices
Validating JSON once before an important operation is good. Building validation into every point where JSON enters or leaves your system is better. These practices apply whether you are building an API, processing data pipelines, or managing configuration files.
Validate at ingestion, not consumption
The right time to validate JSON is when it first enters your system — at the API boundary, at the file upload handler, at the message queue consumer. Validating at consumption (in the function that reads a value deep in your code) means invalid data propagates further before failing, making the error harder to trace. Validate early and reject invalid input at the entry point.
Use a schema, not just a syntax check
Syntax validation is the minimum bar. In any system where JSON carries business-critical data — user records, payment payloads, configuration values — a schema adds a second layer that catches wrong types, missing required fields, and out-of-range values that syntax validation cannot detect. Generate your initial schema from a known-good payload using the JSON Schema Generator and refine it as your data model evolves.
Handle validation errors explicitly
A `JSON.parse()` call wrapped in a try/catch that swallows the error and returns null is worse than no validation — it hides the problem. When JSON validation fails, log the error with the input source, the exact error message, and enough context to reproduce the issue. Return a meaningful error to the caller rather than an empty result that causes a secondary error elsewhere.
- Log the raw input — when JSON validation fails in production, the raw input is the most valuable debugging artifact. Log a truncated version (first 500 chars) with the error.
- Include source context — note where the JSON came from: which API endpoint, which file, which queue message. This turns a generic parse error into an actionable incident.
- Set up alerts for parse failures — a spike in JSON validation errors often signals a breaking change in an upstream API or a deployment that introduced a serialisation bug.
- Test with invalid inputs — include invalid JSON (trailing comma, missing quote, wrong type) in your test suite to confirm your error handling behaves correctly.
Tip
JSON Schema Validator
Validate any JSON payload against a JSON Schema and get rule-level error diagnostics with exact field paths — no install, no uploads.
Key takeaways
- Valid JSON follows RFC 8259 strictly: double-quoted strings only, no trailing commas, no comments, no `undefined`, and no unescaped control characters.
- The JSON Formatter & Validator validates and formats JSON simultaneously, with line-level error diagnostics running entirely in your browser.
- The five most common JSON errors are: trailing commas, single-quoted strings, comments, unescaped control characters, and mismatched brackets — all caught instantly by a validator.
- Syntax validation confirms parseability; JSON Schema validation confirms your data matches its expected contract — both checks serve different purposes.
- Use `JSON.parse()` in a try/catch for in-code validation; use `jq empty` for fast CLI checks in CI pipelines.
- Special formats like JSONL, duplicate-key JSON, and JSON embedded in YAML require format-specific validators rather than a standard JSON parser.
- Validate JSON at ingestion, not consumption — reject invalid data at the entry point before it propagates into your system.