Skip to content
Quasar Tools Logo

How to Validate JSON Online

Learn how to validate JSON online: what valid JSON means, the 5 most common errors and fixes, schema validation, and programmatic checks in JS, Python, and CLI.

DH
Tutorials & How-Tos13 min read2,800 words

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.

< 1sOnline validation timeNo install needed
0 KBData uploadedRuns entirely in browser
5Most common JSON errorsAll caught by a validator

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

JSON5 and JSONC (JSON with Comments) are popular relaxed supersets of JSON that allow comments, trailing commas, and single quotes. If your tool produces these formats, a standard JSON validator will reject them — use a JSON5 or JSONC parser instead, or strip the extensions before validation.

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.

JSON specification, RFC 8259

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

If you only need a yes/no answer — is this valid JSON? — paste your payload and look at the status indicator at the top of the output panel. A green "Valid JSON" badge means the parser accepted the input without errors. A red indicator means something is wrong, and the error details will tell you exactly what.

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.

Open tool

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.

1

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.

Trailing comma — invalid vs valid
json
// ❌ Invalid — trailing comma after last property
{
  "name": "Alice",
  "age": 30,
}

// ✓ Valid — no trailing comma
{
  "name": "Alice",
  "age": 30
}
2

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.

Single quotes — invalid vs valid
json
// ❌ Invalid — single-quoted key and value
{'city': 'London'}

// ✓ Valid — double-quoted key and value
{"city": "London"}
3

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.

Comments — invalid JSON
json
// ❌ Invalid — comments are not part of the JSON spec
{
  // This is the user object
  "name": "Alice",
  "role": "admin" /* elevated permissions */
}
4

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.

Unescaped characters — invalid vs valid
json
// ❌ Invalid — raw newline inside string value
{"message": "line one
line two"}

// ✓ Valid — escaped newline
{"message": "line one\nline two"}
5

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.

Mismatched brackets — invalid vs valid
json
// ❌ 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.

Open tool

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

If you have a JSON payload but no schema yet, the [JSON Schema Generator](/tools/data/converters/json-schema-generator) infers a Draft-07 or Draft 2020-12 schema from your payload automatically. It detects types, required fields, string formats (email, date, URI), and nested object structures. Use the generated schema as a starting point and refine it with additional constraints.

Syntax validation vs. schema validation

AspectSyntax ValidationSchema Validation
What it checksJSON spec conformanceData types, fields, constraints
Tool requiredAny JSON parserJSON Schema validator
Error outputLine/char positionField path + rule violated
CatchesMissing quotes, bad commasWrong type, missing field
When to useAlways — first checkWhen a contract exists
Pass = guaranteeParseable by any JSON libraryMatches 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.

Syntax validation in TypeScript
typescript
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.

Syntax validation in Python
python
import json

def is_valid_json(text: str) -&gt; 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 False

Command 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.

Quick JSON validation from the command line
bash
# 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"
done

Tip

In CI pipelines, use `jq empty` rather than `python3 -m json.tool` for JSON validation. `jq` is faster on large files, produces no output on success (keeping logs clean), and returns a meaningful exit code that your CI system can act on without additional logic.

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

Never use a YAML parser as a substitute for a JSON validator. YAML allows constructs that are not valid JSON — the fact that YAML accepts your input does not confirm that the JSON is spec-compliant. Use a JSON-specific parser for JSON validation, even when the JSON is embedded in a YAML file.

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

When working with third-party API responses, always validate before processing — even for APIs you trust. API providers change response shapes, add new fields, and introduce breaking changes. A schema validator with versioned schemas gives you an early warning of contract changes before they cause silent failures downstream.

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.

Open tool

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.

Frequently Asked Questions

The fastest method is to paste the string into the JSON Formatter & Validator on Quasar Tools — it reports valid or invalid in under a second with no setup. In code, use JSON.parse() wrapped in a try/catch in JavaScript, or json.loads() in a try/except in Python. Both throw an exception on invalid input and return the parsed object on success. For command-line checks, `jq empty input.json` exits with code 0 on valid JSON and code 1 on invalid.

Trailing commas are the single most common JSON error. They appear after the last property in an object or the last element in an array: `{"name": "Alice",}` or `[1, 2, 3,]`. JSON does not allow trailing commas even though JavaScript, Python, and most other languages do. The second most common error is single-quoted strings — JSON requires double quotes for both keys and values.

No. The JSON specification (RFC 8259) explicitly excludes comments. Both `//` line comments and `/* */` block comments are invalid in standard JSON. If you need JSON with comments, consider JSONC (used by VS Code config files) or JSON5, both of which are relaxed supersets. When using these formats, make sure your parser explicitly supports them — a standard JSON parser will reject the file.

Syntax validation checks whether the JSON is well-formed per the RFC 8259 specification — parseable by any standard JSON library. Schema validation checks whether the data inside the JSON conforms to a contract: required fields, correct types, value ranges, string formats. A JSON document can be syntactically valid but semantically wrong — for example, `{"age": "thirty"}` is valid JSON but fails a schema that requires age to be a number.

If your JSON.parse() call appears to succeed but returns null, the input string itself is the JSON text `null` — which is perfectly valid JSON. The value `null` is one of the six JSON value types. If you expected an object or array, the input may have been a null literal rather than a missing or empty string. Wrap JSON.parse() in a function that also checks `typeof result !== "object" || result === null` if you specifically need an object.

A JSONL file contains one JSON object per line and is not a valid JSON document on its own — a standard JSON parser rejects it because the file as a whole does not match the JSON grammar. Use the JSON Lines Validator & Fixer on Quasar Tools, which validates each line individually and reports which line numbers have parse errors. For CLI validation, `jq empty < input.jsonl` also works by reading each line as a separate JSON value.

The JSON specification says behavior is undefined when an object contains duplicate keys — it does not explicitly forbid them, but different parsers handle them differently. Python keeps the last value, some parsers keep the first, and others throw an error. In practice, duplicate keys are almost always a bug. Use the JSON Duplicate Key Detector on Quasar Tools to scan any payload for repeated keys before it causes a silent data-loss issue in your application.

The simplest option is `jq empty filename.json` — it exits with code 0 on valid JSON and code 1 on invalid, with no output on success. For schema validation in CI, use AJV CLI (`ajv validate -s schema.json -d data.json`) or write a short script using Python's jsonschema library. Both integrate cleanly with GitHub Actions, GitLab CI, and other systems that block on non-zero exit codes. Run validation as an early step before any processing to catch issues at the source.

ShareXLinkedIn

Related articles