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.

GoData Integrity

Code

gosnippet
38 lines
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 err before 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

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:`.