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.
Code
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
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
- 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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.