Skip to content

JSON Formatter — PHP source

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

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

<?php
/**
 * JSON formatter — parse, pretty-print (2-space indent), and minify.
 *
 * Language: PHP
 * CosmoDev polyglot showcase port of the `json-formatter` tool.
 * Ported from src/tools/JsonFormatter.tsx — display source, part of CosmoDev's
 * polyglot tool pages.
 *
 * Parses JSON with json_decode, then re-emits it compact for "minify" or
 * indented for "beautify". json_encode is given JSON_UNESCAPED_SLASHES and
 * JSON_UNESCAPED_UNICODE so forward slashes and non-ASCII characters survive
 * unescaped — matching JSON.stringify. PHP's pretty printer indents by four
 * spaces, so the beautified output is re-indented to the requested width
 * (default 2) to match the island. Errors come from json_last_error_msg().
 *
 * Parity caveats versus the TypeScript port: PHP emits floats with at least
 * one decimal ("1.0") where JavaScript would print "1"; integer precision is
 * unbounded where JS caps at 2^53. Object key order is preserved.
 */

/**
 * Format a JSON document the way the live island does.
 *
 * @param string $input  Raw JSON text (whitespace-trimmed).
 * @param string $mode   'beautify' (indented) or 'minify'.
 * @param int    $indent Spaces per nesting level for 'beautify' (default 2).
 * @return array{output:string, error:?string}
 */
function format_json(string $input, string $mode = 'beautify', int $indent = 2): array
{
    if (trim($input) === '') {
        return ['output' => '', 'error' => null];
    }

    // Decode into objects (not assoc arrays) so '{}' round-trips as an object
    // and '[]' round-trips as an array, preserving JSON structure exactly.
    $value = json_decode($input, false);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return ['output' => '', 'error' => json_last_error_msg()];
    }

    // Leave '/' and non-ASCII unescaped, exactly like JSON.stringify.
    $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;

    if ($mode === 'minify') {
        return ['output' => json_encode($value, $flags), 'error' => null];
    }

    // PHP's JSON_PRETTY_PRINT uses a fixed 4-space indent; re-flow every
    // leading run to $indent spaces so the output matches the island.
    $pretty = json_encode($value, $flags | JSON_PRETTY_PRINT);
    $target = $indent;
    $reindented = preg_replace_callback(
        '/^( +)/m',
        static function (array $m) use ($target): string {
            // PHP emits 4 spaces per level, so depth = strlen / 4.
            $depth = intdiv(strlen($m[1]), 4);
            return str_repeat(' ', $depth * $target);
        },
        $pretty,
    );

    return ['output' => (string) $reindented, 'error' => null];
}

// --- Demo ---------------------------------------------------------------------
$sample = '{"name":"CosmoDev","tools":["json","base64"],"free":true,"nested":{"ok":1}}';
$r = format_json($sample, 'beautify');
echo $r['error'] !== null ? "error: {$r['error']}\n" : $r['output'] . "\n";

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 →