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