JSON Valid Compact Indent Payloads
Check payloads with json.Valid, strip whitespace with Compact, and re-indent with Indent — shaping raw JSON without building a decode tree.
Code
package main
import (
"bytes"
"encoding/json"
"fmt"
)
func compact(src []byte) string {
var buf bytes.Buffer
if err := json.Compact(&buf, src); err != nil {
return err.Error()
}
return buf.String()
}
func indent(src []byte) string {
var buf bytes.Buffer
if err := json.Indent(&buf, src, "", " "); err != nil {
return err.Error()
}
return buf.String()
}
func main() {
raw := []byte(`{"name":"Ada","tags":["dev","ops"]}`)
// Valid:只校验合法性,不构造解析树
fmt.Println("valid:", json.Valid(raw))
fmt.Println("broken:", json.Valid([]byte(`{"name":`)))
// Compact:剥掉多余空白
messy := []byte(`{ "name" : "Ada" , "tags" : [ "dev" , "ops" ] }`)
fmt.Println("compact:", compact(messy))
// Indent:按缩进美化输出
fmt.Println(indent(raw))
}The run from entry to exit
Count the functions compact, indent and main as the entire surface area of JSON Valid Compact Indent Payloads.
Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
Watch out for
- Handle
errbefore the other return values; that ordering is the whole contract.
Using it
Signature: func compact(src []byte) string
The demo output is labeled (valid:, broken:, compact:), so every line in the printed output names the step that produced it.
Treat main as the orchestrator calling compact and indent in a fixed order.
Key statements
func compact(src []byte) string {
var buf bytes.Buffer
if err := json.Compact(&buf, src); err != nil {
return err.Error()
}
return buf.String()
}
func indent(src []byte) string {
var buf bytes.Buffer
if err := json.Indent(&buf, src, "", " "); err != nil {
return err.Error()
}
return buf.String()
}
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- How are errors reported?
- The Go way: `err` comes back from each call, and 2 checkpoints here test it before proceeding.
- What does JSON Valid Compact Indent Payloads print when run?
- Run it as a complete program — the output lines carry labels such as `valid:`, `broken:`, `compact:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.