用 Go 读取 JSON 文件需用 os.Open 打开文件,再通过 json.NewDecoder 解析到导出结构体,字段须首字母大写并用 json:"xxx" 标签对齐;嵌套结构和可选字段分别用嵌套结构体和指针处理,注意类型匹配与 UTF-8 编码。
用 Go 读取 JSON 文件很简单,核心是 os.Open + json.Unmarshal,关键在于结构体字段要和 JSON 字段对齐,并注意导出规则和类型匹配。
Go 中只有首字母大写的字段(即导出字段)才能被 json 包读写。建议用结构体字段标签(json:"xxx")显式指定映射关系,避免大小写或下划线不一致导致解析失败。
例如,JSON 内容为:
{ "db_host": "localhost", "db_port": 5432, "debug": true }对应结构体应写成:
type Config struct {
DBHost string `json:"db_host"`
DBPort int `json:"db_port"`
Debug bool `json:"debug"`
}
使用 打开文件,再用
os.Openjson.NewDecoder 或 json.Unmarshal 解析。推荐用 json.NewDecoder,它支持流式读取,内存更友好,也便于处理错误位置。
decoder.Decode(&config) 解析到结构体指针示例代码片段:
f, err := os.Open("config.json")
if err != nil {
log.Fatal(err)
}
defer f.Close()
var cfg Config
if err := json.NewDecoder(f).Decode(&cfg); err != nil {
log.Fatal("JSON decode error:", err)
}
JSON 中常有嵌套对象或缺失字段。Go 支持嵌套结构体,字段标签可加 ,omitempty 表示该字段为空时不参与编码;若字段可能缺失,可设为指针或使用 interface{} + 类型断言,但更推荐用指针+零值判断。
例如:
type Config struct {
Server struct {
Host string `json:"host"`
Port int `json:"port"`
} `json:"server"`
Timeout *int `json:"timeout,omitempty"` // 可选字段,不存在时为 nil
}
之后可通过 if cfg.Timeout != nil 安全判断。
interface{} 或没指定具体类型,务必声明为 int、float64 等明确类型json: 标签是否拼写正确map[string]interface{} 或 json.RawMessage 延迟解析部分字段