← 中文资源

简体中文版本

用 InputOffset 定位 JSON 解码错误

解码失败后读取 Decoder.InputOffset,得到解码器已消费的字节位置,再按这个偏移截取原文,把出错点附近的片段打印出来,比只看错误字符串更快定位。

阅读英文原文

实现说明

用 InputOffset 定位 JSON 解码错误以函数 main为骨架。 for _, doc := range docs 承担全部的逐项处理。检查过的错误绝不放行——2 处 if err != nil,每一处都以 panic(err) 收尾。

使用要点

  • 把它改编进库代码时,通常要把 panic(err) 换成调用方可以分支判断的错误返回值。
  • 直接运行文件,输出会带上标签,比如 failed at byte、near:、decoded keys:——输出的每一行都能指回产生它的那次调用。

常见问题

代码如何报告失败?

通过 panic(err)——2 个检查点测试 err,第一个非 nil 就中止运行。

运行「用 InputOffset 定位 JSON 解码错误」会打印什么?

整个文件跑完,输出行以 failed at byte、near:、decoded keys: 这类前缀开头。

核心语句

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
}

代码示例

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))
}