Developer Documentation
JavaScript
Updated September 19, 2026

Minify JSON in JavaScript

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

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

Quick start#

JavaScript
1function minifyJson(input) {2  return JSON.stringify(JSON.parse(input));3}45console.log(minifyJson({6  "name": "ToolPorta",7  "active": true8}));

Common Operations#

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

Handle errors#

JavaScript
1try {2  const minified = JSON.stringify(JSON.parse(source));3  console.log(minified);4} catch (error) {5  console.error("Invalid JSON", error);6}

Important Notes#

Do not remove whitespace with a regex: spaces inside JSON strings are data. Parse and serialize, or use a JSON-aware compactor.

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: