Developer Documentation
TypeScript
Updated September 19, 2026

Minify JSON in TypeScript

Remove insignificant JSON whitespace safely by parsing and re-serializing in TypeScript.

JSON minification removes insignificant whitespace while preserving the represented data. A parser-based approach is safer than regular expressions because whitespace inside strings must be preserved.

Quick Start#

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

Quick start#

TypeScript
1function minifyJson(input: string): string {2  const value: unknown = JSON.parse(input);3  return JSON.stringify(value);4}56const compact = minifyJson(source);

Common Operations#

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

Safe result type#

TypeScript
1type MinifyResult =2  | { ok: true; value: string }3  | { ok: false; error: string };45function tryMinify(input: string): MinifyResult {6  try {7    return { ok: true, value: JSON.stringify(JSON.parse(input)) };8  } catch (error) {9    return { ok: false, error: error instanceof Error ? error.message : "Invalid JSON" };10  }11}

Important Notes#

For JSON containing integers beyond JavaScript safe integer range, choose a parser that preserves numeric tokens if exact round-tripping is required.

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