实现说明
严格 JSON 解码拒绝未知字段的核心是函数 main。
err 在 2 处被测试,非 nil 就以 panic(err) 中止运行。
使用要点
- 示例不返回错误——任何非 nil 的
err都会让运行立即结束。 - 每一步打印都带着自己的标签:
strict decode:。
常见问题
错误是如何上报的?
以中止方式上报:2 处 err != nil 分支都调用 panic(err),失败在发生地直接终止程序。
运行「严格 JSON 解码拒绝未知字段」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 strict decode: 这类标签。
核心语句
dec.DisallowUnknownFields() // unknown keys now error out directly
代码示例
package main
import (
"encoding/json"
"fmt"
"strings"
)
func main() {
// The config sneaks in an unknown debug field: a default Decode silently ignores it
payload := `{"host":"db.internal","port":5432,"debug":true}`
var cfg struct {
Host string `json:"host"`
Port int `json:"port"`
}
dec := json.NewDecoder(strings.NewReader(payload))
dec.DisallowUnknownFields() // unknown keys now error out directly
if err := dec.Decode(&cfg); err != nil {
fmt.Println("strict decode:", err)
}
// Without the extra field: strict mode passes and the fields actually land in the struct
clean := `{"host":"db.internal","port":5432}`
var good struct {
Host string `json:"host"`
Port int `json:"port"`
}
dec = json.NewDecoder(strings.NewReader(clean))
if err := dec.Decode(&good); err != nil {
panic(err)
}
fmt.Printf("%s:%d\n", good.Host, good.Port)
}