{}JSON-Validator.net
Tutorial · 6 min read

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

"null" is valid JSON
JSON.parse("null") returns null. So is JSON.parse("true"), JSON.parse("42"), and JSON.parse('"hello"').
Empty string is NOT valid JSON
JSON.parse("") throws a SyntaxError. An empty JSON object is {} and an empty array is [].
undefined is not a JSON value
JSON.stringify({a: undefined}) produces {} — undefined values are silently dropped. Use null instead.
Dates are strings in JSON
JSON has no Date type. Dates are typically serialized as ISO 8601 strings: "2026-03-30T10:00:00Z".

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

Related Guides