You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang嵌套Map/Struct YAML解析问题:Unmarshal后Map为空

问题原因

你代码里的TableSpec结构体字段未添加yaml标签,yaml.v3库默认会将结构体字段名转为小写去匹配YAML中的键,但你的YAML里的键是Columns和Where(首字母大写),两者不匹配,导致解析时无法正确赋值,所以Columns是空Map。

解决方案

给结构体字段添加yaml标签,明确指定对应的YAML键名:

package main

import "fmt"
import "gopkg.in/yaml.v3"

type TableSpec struct {
    Columns map[string]string `yaml:"Columns"`
    Where   string            `yaml:"Where"`
}

func main() {
    var t map[string]TableSpec
    
    yamlFile := []byte(`table1:
  Columns:
    col1: mycol
    col2: mycol2
  Where: a = 1`)
      
    err := yaml.Unmarshal(yamlFile, &t)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%v", t["table1"].Columns)
}
补充说明
  • Go结构体字段必须首字母大写(导出字段)才能被外部库(比如yaml.v3)访问,这点你已经做到了。
  • 当YAML中的键名和结构体字段名大小写不一致,或者需要自定义映射关系时,必须通过yaml:"键名"标签来指定对应关系。
  • 运行修改后的代码,会输出map[col1:mycol col2:mycol2],符合预期。

内容的提问来源于stack exchange,提问作者jishi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 23:57:05