How to Validate JSON in JavaScript
JavaScript has no built-in isValidJSON() function. But you can validate JSON reliably using JSON.parse wrapped in a try/catch. This guide shows you every approach — from a one-liner to a full TypeScript validator.
The Basic Approach: JSON.parse + try/catch
JSON.parse() throws a SyntaxError if the input is not valid JSON. Wrapping it in try/catch is the standard way to validate JSON in JavaScript:
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch {
return false;
}
}
// Usage
isValidJSON('{"name": "Alice"}'); // true
isValidJSON("{'name': 'Alice'}"); // false
isValidJSON('not json at all'); // false
isValidJSON('null'); // true (null is valid JSON)
isValidJSON('42'); // true (numbers are valid JSON)Return the Error Message
For debugging, return the error message so you know exactly what went wrong:
function validateJSON(str) {
try {
const data = JSON.parse(str);
return { valid: true, data, error: null };
} catch (e) {
return { valid: false, data: null, error: e.message };
}
}
// Usage
const result = validateJSON('{"name": "Alice",}');
if (!result.valid) {
console.error("Invalid JSON:", result.error);
// Invalid JSON: Expected double-quoted property name in JSON at position 18
}TypeScript Version
A typed version that also extracts line and column numbers from the error message:
type JsonValidationResult =
| { valid: true; data: unknown }
| { valid: false; error: string; line?: number; col?: number };
function validateJSON(input: string): JsonValidationResult {
try {
return { valid: true, data: JSON.parse(input) };
} catch (e) {
const msg = (e as SyntaxError).message;
const line = msg.match(/line (\d+)/i)?.[1];
const col = msg.match(/column (\d+)/i)?.[1];
return {
valid: false,
error: msg,
line: line ? parseInt(line) : undefined,
col: col ? parseInt(col) : undefined,
};
}
}Validating API Responses
When fetching JSON from an API, response.json() already throws on invalid JSON. But if you receive a raw string (e.g. from a webhook or message queue), validate before parsing:
// Fetching JSON — response.json() handles validation
const res = await fetch('/api/data');
const data = await res.json(); // throws SyntaxError if invalid
// Raw string from webhook or queue
function handleWebhook(rawBody: string) {
const result = validateJSON(rawBody);
if (!result.valid) {
console.error(`Invalid webhook payload: ${result.error}`);
return;
}
processPayload(result.data);
}Validating a JSON File in Node.js
import { readFileSync } from 'fs';
function validateJSONFile(path: string) {
try {
const content = readFileSync(path, 'utf-8');
JSON.parse(content);
console.log(`✓ ${path} is valid JSON`);
return true;
} catch (e) {
if (e instanceof SyntaxError) {
console.error(`✗ ${path} is invalid JSON: ${e.message}`);
} else {
console.error(`✗ Could not read ${path}: ${e}`);
}
return false;
}
}
validateJSONFile('./package.json');
validateJSONFile('./data/config.json');Edge Cases to Know
Test Your JSON Without Writing Code
Need a quick sanity check? Paste your JSON into the free online validator — no setup required.
Open JSON Validator