JSON Formatter — JavaScript source
Beautify, minify and validate JSON instantly. Paste, format, copy - all in your browser. Share a link to your exact input.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* JSON formatter - parse, pretty-print (2-space indent), and minify.
*
* Language: JavaScript (ES module)
* CosmoDev polyglot showcase port of the `json-formatter` tool.
* Ported from src/tools/JsonFormatter.tsx - display source, part of CosmoDev's
* polyglot tool pages.
*
* Pure formatting logic extracted from the React island: trims the input,
* JSON.parse's it, and re-stringifies. "beautify" emits with a configurable
* indent (default 2, matching the island's JSON.stringify(parsed, null, 2));
* "minify" emits compact. Parse failures surface the engine's error message
* verbatim (or "Invalid JSON" for non-Error throws); empty/whitespace-only
* input yields empty output with no error. Identical behavior to the typed
* TypeScript port, minus the type annotations.
*/
/**
* Format a JSON document the way the live island does.
*
* @param {string} input Raw JSON text (leading/trailing whitespace ignored).
* @param {'beautify'|'minify'} [mode='beautify'] 'beautify' (indented) or 'minify'.
* @param {number} [indent=2] Indent width for 'beautify'.
* @returns {{ output: string, error: string|null }}
*/
export function formatJson(input, mode = 'beautify', indent = 2) {
const raw = input.trim();
if (!raw) return { output: '', error: null };
try {
const parsed = JSON.parse(raw);
const output =
mode === 'minify'
? JSON.stringify(parsed)
: JSON.stringify(parsed, null, indent);
return { output, 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 →