DEV Community

ZahrionTech
ZahrionTech

Posted on

How to Validate and Format JSON in JavaScript (and a Free Tool That Does It Instantly)

Working with JSON in JavaScript means dealing with one constant problem: is this string actually valid JSON, and how do I make it readable? Whether you're debugging an API response or hand-writing a config file, here are the essential techniques.

Validating JSON with try/catch

JSON.parse() throws a SyntaxError when the input isn't valid JSON, so the standard way to validate is to wrap it in try/catch:

function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch {
    return false;
  }
}

isValidJSON('{"name": "Ada"}');        // true
isValidJSON('{"name": "Ada",}');      // false — trailing comma
isValidJSON("{'name': 'Ada'}");         // false — single quotes aren't valid JSON
Enter fullscreen mode Exit fullscreen mode

Common culprits for invalid JSON: trailing commas, single-quoted strings, comments, and unquoted keys. All are fine in JavaScript object literals, but none are legal in JSON.

Getting the parsed value and error details

A plain boolean isn't always enough. Return the parsed value or the error message instead:

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

const result = validateJSON('{"a": 1');
console.log(result.valid); // false
console.log(result.error); // something like "Expected ',' or '}' after property value..."
Enter fullscreen mode Exit fullscreen mode

Note: exact SyntaxError messages differ between engines (V8, SpiderMonkey, JavaScriptCore), so don't parse the message text programmatically — only rely on the fact that it throws.

Pretty-printing with JSON.stringify

The third argument to JSON.stringify controls indentation:

const data = { name: "Ada", languages: ["JavaScript", "Rust"], active: true };

JSON.stringify(data);           // compact, one line
JSON.stringify(data, null, 2);  // pretty-printed with 2 spaces
JSON.stringify(data, null, "\t"); // indented with tabs
Enter fullscreen mode Exit fullscreen mode

A combined validate-and-format helper

Put it together into one utility you can drop into any project:

function formatJSON(str, indent = 2) {
  try {
    return JSON.stringify(JSON.parse(str), null, indent);
  } catch (err) {
    throw new Error(`Invalid JSON: ${err.message}`);
  }
}

console.log(formatJSON('{"b":2,"a":1}'));
// {
//   "b": 2,
//   "a": 1
// }
Enter fullscreen mode Exit fullscreen mode

For large payloads, JSON.stringify with indentation is fast enough for anything you'd reasonably display, and you can always fall back to the compact form for storage or network transfer.

When you just want it done in your browser

If you'd rather paste and click than write a script, the free JSON validator on Toolstack validates and formats JSON instantly right in your browser — no signup, and everything runs client-side so your data never leaves your device. Handy for quickly checking API responses or config files without opening your editor.

Takeaways

  • JSON.parse() inside try/catch is the canonical way to validate JSON in JavaScript.
  • Never rely on the exact text of the SyntaxError message — it varies by engine.
  • JSON.stringify(value, null, 2) pretty-prints any value in one line of code.
  • For quick one-off checks, a free online JSON validator gets the job done without any setup.

Top comments (0)