Skip to content

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

// json-minify — compact JSON to its smallest valid form. C# port (canonical
// TS: src/lib/json-minify.ts; Go twin: cli/json-minify). Mirrors the JS/PHP
// ports: parse with System.Text.Json, re-emit through a Utf8JsonWriter.
// The writer emits no whitespace by default and rejects NaN/Infinity like
// Go's strict grammar; UnsafeRelaxedJsonEscaping keeps non-ASCII and '/'
// literal (the JSON_UNESCAPED_UNICODE / _SLASHES analogue), so outputs match
// the TS / Go references. Document-backed numbers write their raw source
// text. Invalid JSON -> null.
using System;
using System.IO;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;

public static class JsonMinify
{
    // Compact JSON serialization of input, or null for invalid JSON.
    public static string? Minify(string input)
    {
        try
        {
            using var doc = JsonDocument.Parse(input);
            using var ms = new MemoryStream();
            using var writer = new Utf8JsonWriter(ms, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
            doc.WriteTo(writer);
            writer.Flush(); // dispose-order guard: flush before reading ms
            return Encoding.UTF8.GetString(ms.ToArray());
        }
        catch (JsonException)
        {
            return null; // invalid JSON
        }
    }

    public static void Main()
    {
        Console.WriteLine(Minify("{\n  \"a\": 1,\n  \"b\": [\n    1,\n    2\n  ]\n}")); // {"a":1,"b":[1,2]}
        Console.WriteLine(Minify("{invalid}") ?? "(null — 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 →