Skip to content

JSON Formatter — TypeScript source

Beautify, minify and validate JSON instantly. Paste, format, copy - all in your browser. Share a link to your exact input.

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

// Pure surface of the json-formatter tool (slug: json-formatter). The
// transform itself is JSON.parse + JSON.stringify, but pinning it here with
// edge vectors (duplicate keys, unicode, number canonicalization, error
// surfaces) defines the contract a Go CLI twin must reproduce — notably JS's
// insertion-order key output, which Go maps do not preserve.
export type JsonFormatMode = 'beautify' | 'minify';

export type JsonFormatResult =
  | { output: string; error: null }
  /** Empty or whitespace-only input is NOT an error — the tool shows nothing. */
  | { output: ''; error: null }
  | { output: ''; error: string };

/** Beautify (2-space indent) or minify a JSON document. Whitespace-only input
 *  yields empty output; invalid JSON yields the platform error message. */
export function formatJson(raw: string, mode: JsonFormatMode): JsonFormatResult {
  const text = raw.trim();
  if (!text) return { output: '', error: null };
  try {
    const parsed = JSON.parse(text);
    return { output: JSON.stringify(parsed, null, mode === 'minify' ? 0 : 2), error: null };
  } catch (e) {
    return { output: '', error: e instanceof Error ? e.message : 'Invalid JSON' };
  }
}

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 →