Developer Documentation
JavaScript
Updated September 19, 2026

Format JSON in JavaScript

Pretty-print JSON with predictable indentation and validation in JavaScript.

Formatting JSON means parsing valid JSON and serializing it again with whitespace and indentation that make the structure easier to read. Parsing first also catches malformed input.

Quick Start#

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

Quick start#

JavaScript
1function formatJson(input, spaces = ) {2  const value = JSON.parse(input);3  return JSON.stringify(value, null, spaces);4}56console.log(formatJson('{"name":"ToolPorta","active":true}'));

Common Operations#

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

Preserve arrays and objects#

JavaScript
1const input = '[{"id":1},{"id":2}]';2try {3  const parsed = JSON.parse(input);4  const pretty = JSON.stringify(parsed, null, );5  console.log(pretty);6} catch (error) {7  console.error("Invalid JSON", error);8}

Important Notes#

JSON.parse converts JSON numbers to JavaScript number; very large integers can lose precision. Use a specialized parser if exact numeric literals matter.

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 Formatter in other languages: