Marshal Indent Compacts JSON Output

Format JSON for humans or machines with MarshalIndent and Compact: pretty output takes a custom prefix, and Compact squeezes it back to one line.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
)

func main() {
	// Map keys are sorted at encoding time: active / name / roles regardless of insertion order
	payload := map[string]any{
		"name":  "ada",
		"roles": []string{"admin", "dev"},
		"active": true,
	}

	// MarshalIndent: multi-line indented output with a customizable prefix and indent string
	pretty, err := json.MarshalIndent(payload, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(pretty))

	// Marshal: single-line compact output for logs and transport
	oneline, _ := json.Marshal(payload)
	fmt.Println(string(oneline))

	// json.Compact squeezes an already-indented document back to one line, dropping extra whitespace
	buf := new(bytes.Buffer)
	if err := json.Compact(buf, pretty); err != nil {
		panic(err)
	}
	fmt.Println("compacted:", buf.String())
}

Reading the snippet

Count the function main as the entire surface area of Marshal Indent Compacts JSON Output.

Every err != nil branch (2 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

Caveats

  • Adapting this to library code usually means replacing the panic(err) calls with error returns the caller can branch on.

Using it

Look for the compacted: prefixes when the file runs; they tie each line to its step.

Key statements

if err != nil {
panic(err)
}

Interactive Tools for This Topic

FAQ

How are errors reported?
By aborting: each of the 2 `err != nil` branches calls `panic(err)`, so a failure stops the program at the point it is detected.
What does Marshal Indent Compacts JSON Output print when run?
Run it as a complete program — the output lines carry labels such as `compacted:`.