Developer Documentation
JavaScript
Updated September 19, 2026

Validate JSON in JavaScript

Validate JSON syntax and handle parser errors without mutating the input in JavaScript.

Syntax validation answers one question: can the input be parsed as JSON? It is different from JSON Schema validation, which checks the shape and constraints of already valid JSON data.

Quick Start#

The following example uses the standard JavaScript API or a widely used package for this task.

Syntax validation#

JavaScript
1function validateJson(input) {2  try {3    JSON.parse(input);4    return { valid: true, error: null };5  } catch (error) {6    return { valid: false, error: error instanceof Error ? error.message : "Invalid JSON" };7  }8}910console.log(validateJson('{"ok":true}'));

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

JSON Schema with Ajv#

JavaScript
1// npm install ajv2import Ajv from "ajv";34const ajv = new Ajv();5const schema = { type: "object", required: ["name"], properties: { name: { type: "string" } } };6const validate = ajv.compile(schema);7const valid = validate(JSON.parse(input));8console.log(valid, validate.errors);

Important Notes#

Keep syntax validation and schema validation as separate concepts so callers know whether the failure is malformed JSON or invalid data shape.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement JSON Validator in other languages: