Write NDJSON Lines With json.Encoder
Each json.Encoder.Encode call appends a newline, so looping over records writes one compact JSON object per line that readers can parse row by row.
Code
package main
import (
"bufio"
"encoding/json"
"fmt"
"strings"
)
type Event struct {
Seq int `json:"seq"`
Level string `json:"level"`
Msg string `json:"msg"`
}
func main() {
events := []Event{
{Seq: 1, Level: "info", Msg: "boot"},
{Seq: 2, Level: "warn", Msg: "disk 80%"},
{Seq: 3, Level: "error", Msg: "request failed"},
}
var out strings.Builder
w := bufio.NewWriter(&out)
enc := json.NewEncoder(w)
for _, e := range events {
// Encode 每次调用都在末尾追加一个换行符,正好构成 NDJSON 的行分隔
if err := enc.Encode(e); err != nil {
fmt.Println("encode error:", err)
return
}
}
if err := w.Flush(); err != nil {
fmt.Println("flush error:", err)
return
}
fmt.Print(out.String())
// 每一行都是独立的合法 JSON,读端可以逐行解析
for i, line := range strings.Split(strings.TrimSpace(out.String()), "\n") {
var back Event
if err := json.Unmarshal([]byte(line), &back); err != nil {
fmt.Println("parse error:", err)
return
}
fmt.Printf("line %d seq=%d\n", i+1, back.Seq)
}
}How it works
Everything happens inside the function main.
The loop for _, e := range events is the only repeated construct. Error handling is inline: 3 places test err != nil and branch immediately.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
The primary signature, spelled out, is func main()
Every run emits labeled lines — encode error:, flush error:, parse error: — when the file runs.
Key statements worth quoting
for i, line := range strings.Split(strings.TrimSpace(out.String()), "\n") {
var back Event
if err := json.Unmarshal([]byte(line), &back); err != nil {
fmt.Println("parse error:", err)
return
}
fmt.Printf("line %d seq=%d\n", i+1, back.Seq)
}
for _, e := range events {
// Encode 每次调用都在末尾追加一个换行符,正好构成 NDJSON 的行分隔
if err := enc.Encode(e); err != nil {
fmt.Println("encode error:", err)
return
}
}
Interactive Tools for This Topic
JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.NDJSON to JSON ConverterTurn newline-delimited JSON (JSON Lines) into a single JSON array, reporting the exact line where parsing fails.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.
FAQ
- What does Write NDJSON Lines With json.Encoder print when run?
- Running the file directly is enough — expect labeled output lines such as `encode error:`, `flush error:`, `parse error:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.