Developer Documentation
Go
Updated September 19, 2026

Minify JSON in Go

Remove insignificant JSON whitespace safely by parsing and re-serializing in Go.

JSON minification removes insignificant whitespace while preserving the represented data. A parser-based approach is safer than regular expressions because whitespace inside strings must be preserved.

Quick Start#

The following example uses the standard Go API or a widely used package for this task.

Quick start#

Go
1var out bytes.Buffer2if err := json.Compact(&out, []byte(input)); err != nil {3    return err4}5fmt.Println(out.String())

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Compact bytes#

Go
1func minifyJSON(raw []byte) ([]byte, error) {2    var out bytes.Buffer3    if err := json.Compact(&out, raw); err != nil {4        return nil, err5    }6    return out.Bytes(), nil7}

Important Notes#

json.Compact is ideal here because it validates and removes insignificant whitespace without decoding numbers into Go numeric values.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement JSON Minifier in other languages: