Encoder SetIndent Pretty Streams

json.NewEncoder plus SetIndent streams each value pretty-printed to any writer, appending a newline per Encode without assembling the whole document.

GoData Integrity

Code

gosnippet
23 lines
package main

import (
	"encoding/json"
	"os"
)

func main() {
	// Encoder 直接写 io.Writer;SetIndent 让流式输出的每个值都带缩进
	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")

	events := []any{
		map[string]any{"kind": "deploy", "build": 42},
		map[string]any{"kind": "verify", "ok": true},
	}
	for _, event := range events {
		// 每次 Encode 追加一个换行:多个值可在同一流里逐个落地
		if err := enc.Encode(event); err != nil {
			break
		}
	}
}

How the snippet works

All of the logic lives in the function main.

A single loop drives the file — for _, event := range events. Error handling is inline: 1 place test err != nil and branch immediately.

Caveats

  • Nothing to install: the snippet stays inside the standard library.

Applying it

Its full declaration is func main()

Load-bearing statements

for _, event := range events {
	// 每次 Encode 追加一个换行:多个值可在同一流里逐个落地
	if err := enc.Encode(event); err != nil {
		break
	}
}

Interactive Tools for This Topic

FAQ

How do you run Encoder SetIndent Pretty Streams?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.