How to Validate JSON in JavaScript — 3 Methods Compared

JSON is everywhere — APIs, config files, local storage. But malformed JSON crashes your app silently. Here are three reliable ways to validate JSON before using it.

Method 1: JSON.parse() with Try/Catch

The most straightforward approach. JSON.parse() throws a SyntaxError if the input is not valid JSON. Wrap it in a try/catch block for safe handling:

function validateJSON(str) {
  try {
    JSON.parse(str);
    return { valid: true, data: JSON.parse(str) };
  } catch (e) {
    return { valid: false, error: e.message };
  }
}

// Usage
const result = validateJSON('{"name": "ByteBox"}');
console.log(result.valid); // true

const bad = validateJSON('{name: ByteBox}');
console.log(bad.error); // "Unexpected token n in JSON at position 1"

This catches common issues: missing quotes around keys, trailing commas, single quotes instead of double quotes, and unescaped control characters.

Method 2: The Reviver Parameter

JSON.parse() accepts a second parameter — a reviver function — that transforms the parsed output. You can use this to validate and sanitize in one pass:

function safeParse(str, schema) {
  try {
    const parsed = JSON.parse(str, (key, value) => {
      // Reject unexpected keys
      if (schema && !schema.includes(key) && key !== '') {
        throw new Error(`Unexpected key: ${key}`);
      }
      return value;
    });
    return { valid: true, data: parsed };
  } catch (e) {
    return { valid: false, error: e.message };
  }
}

const allowedKeys = ['name', 'version', 'tools'];
safeParse('{"name":"ByteBox","admin":true}', allowedKeys);
// → { valid: false, error: "Unexpected key: admin" }

Method 3: Use an Interactive JSON Formatter

When you're debugging API responses or inspecting config files, the fastest approach is often an interactive tool. ByteBox's JSON Formatter & Validator validates, beautifies, and minifies JSON in real-time:

  • Syntax validation — highlights the exact line and character where parsing fails
  • Tree view — navigate deeply nested objects with collapsible nodes
  • Copy paths — click any key to copy its dot-notation path
  • 100% client-side — your data never leaves your browser

Try it now: Open JSON Formatter →

Common JSON Errors and Their Fixes

Error Cause Fix
Unexpected token Missing quotes, trailing comma, or unquoted key Wrap keys in double quotes, remove trailing commas
Unexpected end of JSON Truncated or incomplete JSON string Check the complete payload — may be paginated
Unexpected number / string JSON value starts with wrong type in a context expecting another Check the expected schema — arrays vs objects
Bad control character Unescaped newlines or tabs inside strings Use \\n for newlines, \\t for tabs

Related Tools

Once your JSON is valid, you might also need to decode and inspect JWTs (which are Base64-encoded JSON) or compare two JSON payloads side-by-side to find differences between API responses.

All ByteBox tools run 100% client-side. No data is ever uploaded to our servers.