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.
Code
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
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.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.