Skip to content

JSON Minify — PHP 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 PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
/**
 * json-minify — compact JSON to its smallest valid form.
 *
 * Language: PHP (8.1+, standard library only — the JSON extension is always-on
 *           since PHP 8.0)
 * 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 -> null).
 *   - Functionally equivalent to the TS / Go references: same inputs -> same
 *     outputs.
 *   - Self-contained: core JSON extension only (no Composer packages).
 *
 * Behaviour: decode the input, then re-encode with JSON_UNESCAPED_UNICODE (keep
 * non-ASCII literal) and JSON_UNESCAPED_SLASHES (leave '/' alone). Both flags
 * are required to match the Go twin's json.Compact and JS's JSON.stringify,
 * which never emit \uXXXX for BMP characters and never escape '/'.
 *
 * Object identity: decode WITHOUT the $assoc flag so JSON objects round-trip as
 * stdClass rather than array — this preserves the object-vs-array distinction
 * on re-encode ({} stays {}, [] stays []).
 */

declare(strict_types=1);

/**
 * 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.
 */
function minify_json(string $input): ?string
{
    // Decode to stdClass (default $assoc=false) to preserve object identity.
    $decoded = json_decode($input);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return null;
    }
    // Re-encode compact: no unicode/slash escaping. PHP's json_encode emits no
    // whitespace by default, so no separators option is needed.
    $out = json_encode($decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    return $out === false ? null : $out;
}

// --- showcase (the canonical suite lives in src/lib/json-minify.test.ts) ---
// Run with: php src/tool-sources/json-minify/php.php
if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === realpath(__FILE__)) {
    $cases = [
        ['pretty object', "{\n  \"a\": 1,\n  \"b\": [\n    1,\n    2\n  ]\n}", '{"a":1,"b":[1,2]}'],
        ['nested', '{ "x": { "y": [1, 2, 3] } }', '{"x":{"y":[1,2,3]}}'],
        ['already minified', '{"a":1}', '{"a":1}'],
        ['scalar number', '123', '123'],
        ['scalar bool', 'true', 'true'],
        ['scalar null', 'null', 'null'],
        ['unicode preserved', '"héllo 🚀"', '"héllo 🚀"'],
        ['invalid braces', '{invalid}', null],
        ['empty', '', null],
        ['truncated array', '[1, 2,', null],
    ];
    foreach ($cases as [$label, $input, $want]) {
        $got = minify_json($input);
        if ($got !== $want) {
            fwrite(STDERR, "$label: got " . var_export($got, true) . ", want " . var_export($want, true) . "\n");
            exit(1);
        }
    }
    echo "json-minify: showcase OK\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 →