How to Validate JSON in JavaScript
JSON Formatter & Validator
Paste JSON and validate it instantly — errors highlighted with line numbers.
Open JSON Formatter & Validator →Why validate JSON in JavaScript?
JSON.parse() throws a SyntaxError on invalid JSON, which will crash your app if unhandled. Always validate before parsing user-supplied or external JSON.
Method 1 — try/catch (simplest)
The most common approach. Wrap JSON.parse() in try/catch to safely handle invalid input:
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
// With the parsed result and error details
function parseJSON(str) {
try {
return { ok: true, data: JSON.parse(str), error: null };
} catch (e) {
return { ok: false, data: null, error: e.message };
}
}
const result = parseJSON('{"name":"Ada"}');
if (result.ok) {
console.log(result.data.name); // "Ada"
} else {
console.error(result.error);
}Method 2 — validate type after parsing
JSON.parse() accepts primitives like "true" or 42 as valid JSON — but you usually expect an object or array. Add a type check:
function isValidJSONObject(str) {
try {
const parsed = JSON.parse(str);
return typeof parsed === 'object' && parsed !== null;
} catch (e) {
return false;
}
}
function isValidJSONArray(str) {
try {
const parsed = JSON.parse(str);
return Array.isArray(parsed);
} catch (e) {
return false;
}
}Method 3 — JSON Schema validation
For validating that JSON has the right structure — correct fields, correct types — use a JSON Schema library like ajv:
import Ajv from 'ajv';
const ajv = new Ajv();
const schema = {
type: 'object',
required: ['id', 'name', 'email'],
properties: {
id: { type: 'integer' },
name: { type: 'string', minLength: 1 },
email: { type: 'string', format: 'email' }
},
additionalProperties: false
};
const validate = ajv.compile(schema);
const data = JSON.parse(input);
if (validate(data)) {
console.log('Valid!');
} else {
console.error(validate.errors);
}Validating JSON in Node.js vs browser
The try/catch approach works identically in both environments. JSON Schema libraries like ajv work in both too. The only difference is how you read the input — from a file in Node.js, from user input or fetch response in the browser.
import { readFileSync } from 'fs';
function validateJSONFile(path) {
try {
const content = readFileSync(path, 'utf8');
JSON.parse(content);
return { valid: true };
} catch (e) {
return { valid: false, error: e.message };
}
}Frequently asked questions
try { const data = await res.json(); } catch(e) { /* invalid JSON */ }Try it free — no sign-up needed
Runs entirely in your browser. Nothing uploaded, nothing stored.
Open JSON Formatter & Validator →