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.
Code
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
Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.