Track Decode Positions With InputOffset

Read Decoder.InputOffset after a failed decode to learn how far the stream was consumed, then slice the original document around that byte offset.

GoData Integrity

Code

gosnippet
40 lines
package main

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

func main() {
	docs := []string{
		`{"id":1,"tags":["a","b"]}`,
		`{"id":1,"tags":["a",]}`,
	}

	for _, doc := range docs {
		dec := json.NewDecoder(strings.NewReader(doc))
		var payload map[string]any
		err := dec.Decode(&payload)
		if err != nil {
			// InputOffset:解码器已经消费到的字节位置
			off := dec.InputOffset()
			fmt.Printf("failed at byte %d: %v\n", off, err)
			if off > 0 && int(off) <= len(doc) {
				start := int(off) - 1
				fmt.Printf("  near: %q\n", doc[start:])
			}
			continue
		}
		fmt.Println("decoded keys:", len(payload))
	}

	// 合法输入上,偏移停在第一个完整值之后,后续字节留给下一次 Decode
	stream := `{"id":1} {"id":2}`
	dec := json.NewDecoder(strings.NewReader(stream))
	var first map[string]any
	if err := dec.Decode(&first); err != nil {
		panic(err)
	}
	fmt.Printf("first value consumed %d of %d bytes\n", dec.InputOffset(), len(stream))
}

Reading the snippet

Structurally, expect the function main and nothing else.

for _, doc := range docs is the loop that carries the per-item work. Its decode error reports InputOffset — the byte position the decoder reached — prints a near: slice around it, then continues to the next document; only the later single-stream decode panics on failure.

Caveats

  • Nothing beyond the standard library — copied in, it runs as-is.
  • The two failure styles differ on purpose: per-document errors are logged with their byte offset and skipped, while the streaming section treats any decode failure as fatal via panic(err).

Putting it to use

Entry signature: func main()

Look for the failed at byte, near:, decoded keys: prefixes when the file runs; they tie each line to its step.

Core lines

if err != nil {
// InputOffset:解码器已经消费到的字节位置
off := dec.InputOffset()
fmt.Printf("failed at byte %d: %v\n", off, err)
if off > 0 && int(off) <= len(doc) {
start := int(off) - 1
fmt.Printf("  near: %q\n", doc[start:])
}
continue
}

Interactive Tools for This Topic

FAQ

How does the code signal failure?
Through `panic(err)` — the 2 checkpoints test `err` and abort the run on the first non-nil one.
What does Track Decode Positions With InputOffset print when run?
No setup needed: run the file and look for labeled lines like `failed at byte`, `near:`, `decoded keys:` in the output.