JSON Encoder Trailing Newline Versus Marshal

Show that json.Encoder.Encode appends a trailing newline while json.Marshal does not, so hashing, diffing, and bytes.Equal checks diverge.

GoData Integrity

Code

gosnippet
32 lines
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
)

func main() {
	value := map[string]int{"retries": 3, "timeout_ms": 1500}

	marshaled, err := json.Marshal(value)
	if err != nil {
		panic(err)
	}

	var encoded bytes.Buffer
	enc := json.NewEncoder(&encoded)
	if err := enc.Encode(value); err != nil {
		panic(err)
	}

	// Encode 在每次调用后追加一个 trailing newline,Marshal 不会
	fmt.Println("marshal len:", len(marshaled))
	fmt.Println("encode  len:", encoded.Len())
	fmt.Printf("encode last byte: %q\n", encoded.Bytes()[encoded.Len()-1])
	fmt.Println("bytes.Equal:", bytes.Equal(marshaled, encoded.Bytes()))

	// 去掉换行后两者逐字节一致(map 键序两路都按字典序输出)
	trimmed := bytes.TrimSuffix(encoded.Bytes(), []byte{'\n'})
	fmt.Println("equal after trim:", bytes.Equal(marshaled, trimmed))
}

The anatomy of the file

JSON Encoder Trailing Newline Versus Marshal is built around the function main.

Failure handling is panic(err): 2 checkpoints abort the program at the point a problem is detected.

Points of care

  • No package manager in the path — every call lands on a built-in API.
  • panic(err) is the only failure path here: the first problem stops the program.

Putting it to use

Signature: func main()

The run emits 5 labeled sections — marshal len:, encode len:, encode last byte:, bytes.Equal:, equal after trim: — one per step.

Core lines

if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
It stops. All 2 `if err != nil` branches ends in `panic(err)` — nothing continues past a failed call.
What does JSON Encoder Trailing Newline Versus Marshal print when run?
The script runs standalone; its 5 labeled outputs include `marshal len:`, `encode len:`, `encode last byte:`.