Article

How to Validate JSON in JavaScript

Validate JSON in JavaScript with JSON.parse() and try/catch. Get line and column from errors. Use an online validator for quick checks and user-friendly messages.

Basic Validation with JSON.parse

Call JSON.parse(str). If the string is valid JSON, it returns the parsed value. If not, it throws a SyntaxError. Wrap it in try/catch to validate without throwing:

try {
  const data = JSON.parse(str);
  console.log('Valid JSON', data);
} catch (e) {
  console.error('Invalid JSON:', e.message);
}

Getting Line and Column from the Error

The error message often includes "at position N". To convert position to line and column, count newlines in the substring before that index. Our JSON validator does this and shows "line X, column Y" so users can fix the exact spot. In code you can do the same: parse the message for the position, then slice the string and split by newlines to get line/column.

When to Use an Online Validator

For quick checks, paste JSON into our JSON validator. You get an immediate valid/invalid result and, on error, the line and column. No code required. For production apps, use try/catch and optionally extract position/line/column from the error to show a helpful message. Validate before storing or sending user input.

Related Reading

For fixing the actual syntax errors see fix unexpected token in JSON and JSON parse error at position explained. For formatting or comparing JSON see our formatter and diff tool.

Summary

Validate JSON in JavaScript with JSON.parse() in a try/catch. Use our JSON validator for quick checks and human-readable line/column errors. For more tools see developer tools.