Skip to content

JSON Minify — JavaScript source

Remove all whitespace from JSON for the most compact serialization. Validates as it minifies, runs entirely in your browser, with a shareable link to your exact input.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

/**
 * json-minify - compact JSON to its smallest valid form.
 *
 * Language: JavaScript (ES2020+, standard library only)
 * Source:   CosmoDev polyglot showcase port of the JSON Minify tool, mirrored
 *           from src/lib/json-minify.ts (the canonical TypeScript implementation)
 *           and cli/json-minify/json-minify.go (the live Go CLI twin).
 * License:  display source - part of CosmoDev's polyglot tool pages.
 *
 * Design goals:
 *   - Pure + deterministic; never throws (invalid JSON yields null).
 *   - Functionally equivalent to the TS / Go references: same inputs -> same
 *     outputs. JSON.parse + JSON.stringify is the canonical minify pipeline.
 *   - Self-contained: the language's built-in JSON is the only dependency.
 *
 * Behaviour: parse the input as JSON, then re-serialize with no inter-token
 * whitespace. Object key order and original number/string spellings are
 * preserved by JSON.stringify. Non-ASCII code points are left as-is (never
 * escaped to \uXXXX), matching the Go twin's json.Compact.
 */

/**
 * Compact JSON serialization of `input`, or null if it is not valid JSON.
 *
 * Mirrors the TS minifyJson and Go Minify: parse then re-emit with no
 * insignificant whitespace. Never throws.
 *
 * @param {string} input
 * @returns {string | null}
 */
function minifyJson(input) {
  try {
    return JSON.stringify(JSON.parse(input));
  } catch {
    return null;
  }
}

import { fileURLToPath } from 'node:url';
import { resolve } from 'node:path';

// --- showcase (the canonical suite lives in src/lib/json-minify.test.ts) ---
// Run with: node src/tool-sources/json-minify/javascript.js
function main() {
  const eq = (got, want, label) => {
    if (got !== want) {
      console.error(`${label}: got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
      process.exitCode = 1;
    }
  };

  // 1. whitespace stripped, key order preserved.
  eq(
    minifyJson('{\n  "a": 1,\n  "b": [\n    1,\n    2\n  ]\n}'),
    '{"a":1,"b":[1,2]}',
    'pretty object',
  );
  // 2. nested structures collapse recursively.
  eq(minifyJson('{ "x": { "y": [1, 2, 3] } }'), '{"x":{"y":[1,2,3]}}', 'nested');
  // 3. already-compact input passes through unchanged.
  eq(minifyJson('{"a":1}'), '{"a":1}', 'already minified');
  // 4. top-level scalars are valid JSON.
  eq(minifyJson('123'), '123', 'scalar number');
  eq(minifyJson('true'), 'true', 'scalar bool');
  eq(minifyJson('null'), 'null', 'scalar null');
  // 5. non-ASCII strings stay unescaped.
  eq(minifyJson('"héllo 🚀"'), '"héllo 🚀"', 'unicode preserved');
  // 6. invalid JSON -> null, never throws.
  eq(minifyJson('{invalid}'), null, 'invalid braces');
  eq(minifyJson(''), null, 'empty');
  eq(minifyJson('[1, 2,'), null, 'truncated array');

  if (!process.exitCode) console.log('json-minify: showcase OK');
}

// Run the showcase when executed directly. ESM (the project is
// "type":"module"): the entry point is identified by comparing import.meta.url
// against process.argv[1].
if (resolve(process.argv[1] ?? '') === fileURLToPath(import.meta.url)) {
  main();
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →