JSON validation is not one check. It is usually three different questions that get collapsed into the same sentence:
- Does the text parse as JSON?
- Does the parsed value match the shape your API, config file, or database importer expects?
- Does the value make sense for your product rules?
Those questions need different tools. JSON.parse() can prove that {"email":"ada@example.com"} is syntactically valid JSON. It cannot prove that email is required, that age must be an integer, or that the user ID exists in your database. For that, you need JSON Schema and, often, a few application-level checks after schema validation passes.
This guide keeps those boundaries clear, because most validation bugs come from using the right tool for the wrong layer.
Quick Answer
To validate JSON syntax, parse it with a real JSON parser:
function validateJsonSyntax(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (error) {
return {
ok: false,
error: error instanceof SyntaxError ? error.message : String(error),
};
}
}
If the parse succeeds, the text is valid JSON. If it throws, the text is not valid JSON.
To validate structure, parse first, then validate the parsed value against JSON Schema with a library such as Ajv in JavaScript or jsonschema in Python.
For a no-install syntax check, paste the payload into JSON Validator. It runs in your browser, uses strict JSON parsing, highlights the error location, and formats valid JSON locally.
Validation Means Different Things
Before choosing a tool, name the failure you are trying to catch.
| Question | Example failure | Tool |
|---|---|---|
| Does it parse? | {"name":"Ada",} has a trailing comma. |
JSON parser, JSON.parse, json.loads, jq empty, browser validator |
| Does it match the contract? | email is missing, or age is a string instead of an integer. |
JSON Schema, Ajv, jsonschema, OpenAPI validators |
| Is it allowed in this system? | The user ID is valid JSON but does not exist, or a role change is not permitted. | Application code, database checks, authorization rules |
Treat syntax validation as the gate at the door. It tells you whether the text can become a JSON value at all. Schema validation is the next gate. It tells you whether that value has the fields, types, and constraints your program expects.
Validate JSON Syntax in JavaScript
The most reliable JavaScript validator is the parser already built into the runtime. Do not pre-check JSON with regular expressions or string cleanup. Try the parse and handle the error.
function parseJsonOrReport(text) {
try {
const value = JSON.parse(text);
return { ok: true, value };
} catch (error) {
return {
ok: false,
message: error.message,
};
}
}
parseJsonOrReport('{"name":"Ada"}');
// { ok: true, value: { name: "Ada" } }
parseJsonOrReport('{"name":"Ada",}');
// { ok: false, message: "Expected double-quoted property name in JSON at position 14" }
If you only need a boolean, discard the parsed value:
function isValidJson(text) {
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
In production code, I usually keep the parsed value. Parsing once for validation and then parsing again for actual use is wasted work, and it gives two places for error handling to drift.
Syntax Mistakes a Parser Actually Catches
Strict JSON is smaller than JavaScript object literal syntax. These snippets are common in tickets and logs, but all of them are invalid JSON:
{"name":"Ada",}
Trailing commas are not allowed.
{'name':'Ada'}
Strings and object keys must use double quotes.
{name: "Ada"}
Object keys must be quoted strings.
{
// copied from a config file
"name": "Ada"
}
Comments are not part of JSON. They may work in JSONC files such as some editor settings, but they will fail in strict API JSON.
{"value": undefined}
undefined, NaN, and Infinity are JavaScript values, not JSON values. Use null, a number, a string, a boolean, an object, or an array.
One thing syntax validation may not protect you from is duplicate keys:
{"role":"user","role":"admin"}
This is syntactically accepted by many parsers, but the last value usually wins when it becomes a JavaScript object. If duplicate keys matter for your pipeline, catch them with a stricter parser or a custom ingest check.
Validate a Fetch Response Before Parsing It
Many "invalid JSON" errors are not caused by a bad JSON document. They are caused by parsing the wrong response. A login page, proxy error, CDN block page, or stack trace often starts with <, which is why developers see Unexpected token < in JSON at position 0.
When you read API responses, check the HTTP status and content type before blaming the JSON parser:
async function readJsonResponse(response) {
const text = await response.text();
const contentType = response.headers.get('content-type') || '';
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${text.slice(0, 120)}`);
}
if (!contentType.includes('application/json')) {
throw new Error(`Expected JSON, got ${contentType || 'no content-type'}`);
}
try {
return JSON.parse(text);
} catch (error) {
throw new Error(`Invalid JSON response: ${error.message}`);
}
}
This pattern gives you better bug reports. Instead of "JSON parse failed," you can see "HTTP 502" or "Expected JSON, got text/html" and fix the real upstream problem.
Validate JSON in Python
Python's built-in json module gives you the same first layer: syntax validation through parsing. json.loads() raises json.JSONDecodeError with line and column details.
import json
def validate_json_syntax(text):
try:
return {"ok": True, "value": json.loads(text)}
except json.JSONDecodeError as error:
return {
"ok": False,
"message": error.msg,
"line": error.lineno,
"column": error.colno,
}
print(validate_json_syntax('{"name": "Ada"}'))
print(validate_json_syntax('{"name": "Ada",}'))
That line and column are worth keeping in CLI tools and import scripts. "Invalid JSON" is a dead end. "Trailing comma at line 18 column 2" is something a teammate can fix in ten seconds.
Validate a JSON File on the Command Line
For scripts and CI, use a command that exits non-zero on invalid JSON.
With jq:
jq empty data.json
jq empty parses the file and prints nothing when the file is valid. If the file is invalid, it prints an error and exits with a failure status.
With Python, no extra install required:
python3 -m json.tool data.json > /dev/null
To validate a folder of JSON files:
find . -name '*.json' -not -path './node_modules/*' -print0 |
while IFS= read -r -d '' file; do
jq empty "$file" || exit 1
done
That style works well for repos with config files, seed data, localization dictionaries, fixtures, and hand-edited schema examples.
Validate JSON in the Browser
Use fixjson's JSON Validator when you want a quick syntax check without writing a script. It is intentionally strict:
- It checks whether the input is valid JSON, not whether it is a JavaScript object literal.
- It reports the line and column for syntax errors.
- It highlights the failing location so you do not have to count characters by hand.
- If the input is valid, it formats the JSON locally with 2-space or 4-space indentation.
- It can sort object keys in the formatted output when you need stable diffs.
The core validation and formatting flow runs in your browser. That matters when you are checking a token response, webhook payload, internal config, or customer-supplied sample that should not be uploaded just to find a missing quote.
One important boundary: /json-validate is a syntax validator. It does not enforce JSON Schema. If the JSON parses but your API rejects it, move to the schema validation sections below.
Validate JSON in VS Code and Other Editors
Editors catch many JSON mistakes before you even run the file. VS Code, for example, underlines syntax errors in .json files and can attach schemas for structural validation.
A file can point to a schema directly:
{
"$schema": "./user.schema.json",
"id": 42,
"email": "ada@example.com"
}
Or a project can map file patterns to schemas in editor settings. That is useful for files such as *.theme.json, *.manifest.json, or internal configuration files where the filename tells the editor which contract applies.
Be careful with JSONC. Some editor and TypeScript config files allow comments and trailing commas. API payloads, package registry metadata, and most import/export files usually expect strict JSON. A file that feels valid in an editor can still fail when it is sent to a strict parser.
Validate Structure with JSON Schema
JSON Schema starts after syntax validation. It says what a parsed JSON value should look like:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "email", "age"],
"additionalProperties": false,
"properties": {
"id": { "type": "integer" },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 13 }
}
}
This schema accepts an object with exactly id, email, and age. It rejects missing required fields, extra fields, a string ID, and an age below 13.
Validate JSON Schema in JavaScript with Ajv
Ajv is a common choice for JavaScript and TypeScript projects:
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
const userSchema = {
$schema: 'https://json-schema.org/draft/2020-12/schema',
type: 'object',
required: ['id', 'email', 'age'],
additionalProperties: false,
properties: {
id: { type: 'integer' },
email: { type: 'string', format: 'email' },
age: { type: 'integer', minimum: 13 },
},
};
const ajv = new Ajv({ allErrors: true });
addFormats(ajv);
const validate = ajv.compile(userSchema);
const data = JSON.parse('{"id":42,"email":"ada@example.com","age":37}');
if (!validate(data)) {
console.error(validate.errors);
}
The ajv-formats package is easy to forget. Without it, formats such as email, uri, and date-time may not behave the way you expect in modern Ajv setups.
Validate JSON Schema in Python
In Python, the jsonschema package can validate a parsed value and return detailed paths for each failure:
import json
from jsonschema import Draft202012Validator
schema = {
"type": "object",
"required": ["id", "email", "age"],
"additionalProperties": False,
"properties": {
"id": {"type": "integer"},
"email": {"type": "string", "format": "email"},
"age": {"type": "integer", "minimum": 13},
},
}
data = json.loads('{"id": 42, "email": "ada@example.com", "age": 37}')
validator = Draft202012Validator(schema)
errors = sorted(validator.iter_errors(data), key=lambda error: error.path)
for error in errors:
path = ".".join(str(part) for part in error.path) or "<root>"
print(f"{path}: {error.message}")
For command-line import jobs, printing the JSON path is more useful than printing the whole bad payload. It lets the owner fix items.17.price without searching a 2 MB file.
What JSON Schema Does Not Validate
Schema validation is powerful, but it is not your whole business rule system.
A schema can say:
emailis required.agemust be an integer.statusmust be one ofdraft,active, orarchived.itemsmust be an array with at least one item.
It usually should not be asked to decide:
- whether the email belongs to an existing account,
- whether the current user can update this resource,
- whether a coupon code is still redeemable,
- whether two IDs are allowed to be linked,
- whether the value is safe to store without redaction.
Do syntax validation first, schema validation second, and domain validation third. The order keeps error messages clean and prevents business logic from running against values that were never valid JSON in the first place.
Validate JSON in CI
At minimum, CI should reject malformed JSON files. A simple package script is enough for many JavaScript projects:
{
"scripts": {
"check:json": "find . -name '*.json' -not -path './node_modules/*' -print0 | xargs -0 -n1 jq empty"
}
}
Then run it in CI:
npm run check:json
For Python projects that already use pre-commit, add the built-in JSON check from pre-commit-hooks:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: check-json
If your repo contains schemas, add a second CI step that validates important fixtures, examples, localization files, or API contract samples against those schemas. Syntax checks catch broken text. Schema checks catch broken shape.
Common JSON Validation Errors
Use the error text as a clue. It usually points to a specific class of mistake.
| Error shape | Likely cause | What to check |
|---|---|---|
Unexpected token < |
You parsed HTML as JSON. | Check HTTP status, login redirects, proxy errors, and content-type. |
Unexpected token u |
You parsed undefined or an empty browser storage value. |
Log the raw value before parsing. |
Trailing comma before '}' |
Extra comma after the last object property. | Remove the comma before the closing brace. |
Expected string key |
An object key is unquoted or single-quoted. | Use double quotes around every key. |
Unterminated string literal |
A quote is missing, or a newline slipped into a string. | Check the previous line, not only the highlighted one. |
Unexpected end of input |
The JSON was truncated or a bracket was never closed. | Compare opening and closing braces, or re-fetch the response. |
| Valid JSON, API still rejects it | Syntax is fine, contract is not. | Run JSON Schema or OpenAPI validation. |
format did not reject an email |
The validator treats formats as annotations or lacks a formats plugin. | Enable format validation, such as ajv-formats for Ajv. |
If you want repair suggestions rather than a yes/no result, use JSON Fix. If you want to understand a parser message in detail, these guides cover the usual cases:
- Unexpected token errors
- Unexpected end of input
- Trailing commas in JSON
- Single quotes vs JSON double quotes
- "[object Object] is not valid JSON"
Frequently Asked Questions
How do I check if a string is valid JSON?
Pass it to JSON.parse() inside a try/catch in JavaScript, or json.loads() inside a try/except in Python. If parsing succeeds, the string is valid JSON. Keep the parsed value if you will use it next.
Can I validate JSON with a regular expression?
No. JSON has nested arrays and objects, escaped characters, strings, numbers, booleans, and null. Use a real parser such as JSON.parse, json.loads, jq, or the browser validator.
What is the difference between validating and parsing JSON?
Parsing converts JSON text into a runtime value. Syntax validation is the act of proving that parse can happen. In practice, a successful parse is the syntax validation step.
What does JSON Schema validate?
JSON Schema validates the shape of parsed JSON: required fields, allowed types, enum values, numeric ranges, array lengths, object properties, and similar contract rules.
Does JSON Schema validate email and date formats?
It can, but format behavior depends on the validator and its configuration. In Ajv, add ajv-formats if you expect formats such as email, uri, and date-time to be checked.
Can valid JSON still be wrong?
Yes. {"id":"42"} is valid JSON, but it may be wrong for an API that requires id to be an integer. Valid syntax only means the text follows the JSON grammar.
How do I validate JSON in CI?
Run a syntax check such as jq empty or python3 -m json.tool over your .json files. For contract files, fixtures, and API examples, add a JSON Schema validation step too.
Is it safe to use an online JSON validator?
It depends on the tool and the data. The core fixjson.org validator runs in your browser, so routine syntax checking does not require uploading the payload. Still redact passwords, tokens, cookies, private keys, and customer data before pasting JSON into any website, chat, ticket, or screenshot.
Validate JSON Now
Use JSON Validator when you need a quick syntax check with line and column feedback. Use JSON Fix when the payload is broken and you want repair suggestions.
Related guides:
- What Is JSON Schema?
- How to Format JSON
- How to Minify JSON
- How to Compare Two JSON Files
- What Is JSON?
Sources
- RFC 8259 and ECMA-404 for the JSON grammar
- MDN JSON.parse
- Python json module
- jq manual
- JSON Schema
- Ajv
- ajv-formats
- python-jsonschema
Last reviewed July 2026.