Developer Documentation
Go
Updated September 19, 2026

Format JSON in Go

Pretty-print JSON with predictable indentation and validation in Go.

Formatting JSON means parsing valid JSON and serializing it again with whitespace and indentation that make the structure easier to read. Parsing first also catches malformed input.

Quick Start#

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

Quick start#

Go
1package main23import (4    "bytes"5    "fmt"6)78func main() {9    var out bytes.Buffer10    if err := json.Indent(&out, []byte(input), "", "  "); err != nil {11        panic(err)12    }13    fmt.Println(out.String())14}

Common Operations#

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

Compact or indent raw JSON#

Go
1var pretty bytes.Buffer2if err := json.Indent(&pretty, raw, "", "  "); err != nil {3    return err4}56var compact bytes.Buffer7if err := json.Compact(&compact, raw); err != nil {8    return err9}

Important Notes#

json.Indent and json.Compact operate on raw JSON bytes, which avoids converting numbers into float64 through interface{}.

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 Formatter in other languages: