Developer Documentation
TypeScript
Updated September 19, 2026

Format JSON in TypeScript

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

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 TypeScript API or a widely used package for this task.

Quick start#

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

Common Operations#

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

Typed boundary#

TypeScript
1function parseJson(input: string): unknown {2  return JSON.parse(input) as unknown;3}45const value = parseJson(source);6// Validate/narrow `value` before treating it as an application type.

Important Notes#

Do not cast parsed JSON directly to trusted domain types without runtime validation; TypeScript types do not validate external data.

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: