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