Classify JSON Decode Errors With As

errors.As distinguishes malformed JSON from type mismatches: json.SyntaxError reports the failing byte offset and UnmarshalTypeError names the target field.

GoData Integrity

Code

gosnippet
41 lines
package main

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

type Metric struct {
	Name  string  `json:"name"`
	Value float64 `json:"value"`
}

func decode(raw []byte) {
	var m Metric
	err := json.Unmarshal(raw, &m)
	if err == nil {
		fmt.Printf("ok: %+v\n", m)
		return
	}

	// 两类解码错误要区别对待:
	// *json.SyntaxError → 文本不是合法 JSON,Offset 指向出错字节
	// *json.UnmarshalTypeError → JSON 合法但字段类型对不上目标结构
	var syntaxErr *json.SyntaxError
	var typeErr *json.UnmarshalTypeError
	switch {
	case errors.As(err, &syntaxErr):
		fmt.Printf("syntax error at byte %d: %v\n", syntaxErr.Offset, syntaxErr)
	case errors.As(err, &typeErr):
		fmt.Printf("type error on field %q: %v\n", typeErr.Field, typeErr)
	default:
		fmt.Println("other decode error:", err)
	}
}

func main() {
	decode([]byte(`{"name": "rps", "value": 12.5}`)) // 正常
	decode([]byte(`{"name": "rps", "value": "high"}`)) // 类型不匹配
	decode([]byte(`{"name": "rps"`))                  // 截断的语法错误
}

How execution unfolds

Classify JSON Decode Errors With As keeps everything in the functions decode and main.

Applying it

Entry signature: func decode(raw []byte)

The demo output is labeled (ok:, syntax error at byte, type error on field), so the printed output reads as a trace of the operations performed.

The sequence decode lives in main; running the file triggers it.

Statements that matter

decode([]byte(`{"name": "rps", "value": "high"}`)) // 类型不匹配

Interactive Tools for This Topic

FAQ

What does Classify JSON Decode Errors With As print when run?
Run it as a complete program — the output lines carry labels such as `ok:`, `syntax error at byte`, `type error on field`.