
最近在搬砖的过程中遇到了一个在 Go 代码中 YAML 转 JSON 引发报错的小问题随手记录一下。场景是这样的我实现了一个功能支持用户上传 YAML/JSON 格式的文档为了方便我会将文档全部转为 JSON 格式再来统一处理。平时经常操作 YAML也经常操作 JSON但二者互转的场景不怎么会遇到所以因为一时疏忽就遇到了问题。使用 yaml.v3 包处理 YAML首先假设我们有如下一段 YAML 文档object: a: 1 1: 2 1: 3 key: value array: - null_value: - boolean: true - integer: 1这个 YAML 文档是一个对象结构并且对象内部还包含了一个数组。细心观察你会发现对象中有两个key比较近似一个是数字类型的1另一个是字符串类型的1这点需要注意。在 Go 语言中可以使用yaml.v3来处理 YAML 文档使用内置的encoding/json来处理 JSON 内容。我们来编写一段 Go 代码将上面这个 YAML 文档转换成 JSON 对象。实现如下package main import ( encoding/json fmt log github.com/icza/dyno // 用于递归转换 map[interface{}] map[string] gopkg.in/yaml.v3 // YAML 解析库 ) func main() { yamlExample : object: a: 1 1: 2 1: 3 key: value array: - null_value: - boolean: true - integer: 1 // 解析 YAML var data interface{} if err : yaml.Unmarshal([]byte(yamlExample), data); err ! nil { log.Fatalf(YAML parse error: %v, err) } fmt.Printf(Type: %T\nValue: %#v\n, data, data) fmt.Println(--------------------------) // 关键递归转换 map 键类型interface{} → string convertedData : dyno.ConvertMapI2MapS(data) // 转换为 JSON jsonData, err : json.Marshal(convertedData) if err ! nil { log.Fatalf(JSON convert error: %v, err) } fmt.Printf(Type: %T\nValue: %s\n, jsonData, jsonData) }这段代码用于将 YAML 格式的文档解析并转换成 JSON 格式。执行示例代码得到输出如下$ go run main.go 2025/07/31 23:22:49 YAML parse error: yaml: unmarshal errors: line 5: mapping key 1 already defined at line 4 exit status 1根据输出结果可以发现代码直接就报错了。错误信息提示1这个key之前已经存在。此时我们可以尝试注释掉1: 3这个键值对yamlExample : object: a: 1 1: 2 # 1: 3 key: value array: - null_value: - boolean: true - integer: 1 然后再次执行示例代码得到输出如下$ go run main.go Type: map[string]interface {} Value: map[string]interface {}{object:map[interface {}]interface {}{a:1, array:[]interface {}{map[string]interface {}{null_value:interface {}(nil)}, map[string]interface {}{boolean:true}, map[string]interface {}{integer:1}}, key:value, 1:2}} -------------------------- Type: []uint8 Value: {object:{1:2,a:1,array:[{null_value:null},{boolean:true},{integer:1}],key:value}}这一次我们成功的将 YAML 转换换成了 JSON。由此可见在 Go 语言中使用yaml.v3包解析 YAML 时1和1会被认为是对象的同一个key会引发冲突。此外你应该也已经发现示例代码中通过yaml.Unmarshal反序列化出来的的data对象并没有直接交给json.Marshal去处理而是中间经过了dyno.ConvertMapI2MapS(data)的转换之后再进行 JSON 序列化操作。如果我们去掉dyno.ConvertMapI2MapS(data)这行代码写成这样package main import ( encoding/json fmt log gopkg.in/yaml.v3 // YAML 解析库 ) func main() { yamlExample : object: a: 1 1: 2 # 1: 3 key: value array: - null_value: - boolean: true - integer: 1 // 解析 YAML var data interface{} if err : yaml.Unmarshal([]byte(yamlExample), data); err ! nil { log.Fatalf(YAML parse error: %v, err) } fmt.Printf(Type: %T\nValue: %#v\n, data, data) fmt.Println(--------------------------) // 转换为 JSON jsonData, err : json.Marshal(data) if err ! nil { log.Fatalf(JSON convert error: %v, err) } fmt.Printf(Type: %T\nValue: %s\n, jsonData, jsonData) }执行示例代码得到输出如下$ go run main.go Type: map[string]interface {} Value: map[string]interface {}{object:map[interface {}]interface {}{a:1, array:[]interface {}{map[string]interface {}{null_value:interface {}(nil)}, map[string]interface {}{boolean:true}, map[string]interface {}{integer:1}}, key:value, 1:2}} -------------------------- 2025/07/31 23:34:26 JSON convert error: json: unsupported type: map[interface {}]interface {} exit status 1这一次程序同样会报错。不过错误信息发生了变化这次不再是yaml.Unmarshal报错而是json.Marshal出现报错。错误信息提示json.Marshal不支持map[interface {}]interface {}类型对象的序列化操作。我们可以整理一下yaml.Unmarshal反序列化得到的对象这样更加清晰map[string]interface{}{ object: map[interface{}]interface{}{ a: 1, array: []interface{}{ map[string]interface{}{ null_value: interface{}(nil), }, map[string]interface{}{ boolean: true, }, map[string]interface{}{ integer: 1, }, }, key: value, 1: 2, }, }可以看到这个对象内部嵌套了map[interface {}]interface {}类型。因为json.Marshal接收的对象key必须是string类型而 Go 语言中map的key只要是可比较的类型即可这就包括了可比较的interface{}类型。而代码中dyno.ConvertMapI2MapS函数的作用正是将map[interface {}]interface {}类型转换成map[string]interface {}类型。dyno.ConvertMapI2MapS函数源码如下// ConvertMapI2MapS walks the given dynamic object recursively, and // converts maps with interface{} key type to maps with string key type. // This function comes handy if you want to marshal a dynamic object into // JSON where maps with interface{} key type are not allowed. // // Recursion is implemented into values of the following types: // -map[interface{}]interface{} // -map[string]interface{} // -[]interface{} // // When converting map[interface{}]interface{} to map[string]interface{}, // fmt.Sprint() with default formatting is used to convert the key to a string key. func ConvertMapI2MapS(v interface{}) interface{} { switch x : v.(type) { case map[interface{}]interface{}: // 目标转换类型需要把 key 为 interface{} 类型的转换成 string m : map[string]interface{}{} for k, v2 : range x { switch k2 : k.(type) { case string: // 如果 key 已经是 string 类型则直接使用 m[k2] ConvertMapI2MapS(v2) default: // 如果 key 是其他类型则需要转换成 string m[fmt.Sprint(k)] ConvertMapI2MapS(v2) } } v m case []interface{}: // 递归处理数组元素 for i, v2 : range x { x[i] ConvertMapI2MapS(v2) } case map[string]interface{}: // key 已经是 string仅递归处理 value for k, v2 : range x { x[k] ConvertMapI2MapS(v2) } } return v }这个函数代码还是比较清晰的就是递归处理map[interface{}]interface{}类型将其转换成目标类型map[string]interface {}。那么为什么yaml.Unmarshal返回的对象中会包含map[interface{}]interface{}类型而不能直接全部都用map[string]interface {}类型呢其实在yaml.v3官方代码仓库 issues/137 中还真有人问过作者作者的回复是Unfortunately not.. Unlike json, yaml can take keys of arbitrary types.即不能这么做因为 YAML 规范是允许任意类型值作为对象key的所以这也是为什么在我提供的 YAML 示例文档中1: 2和1: 3同时存在是合法的。所以你在使用 Go 语言操作 YAML 转 JSON 时保险起见一定要加上dyno.ConvertMapI2MapS函数来避免直接将map[interface{}]interface{}类型传递给json.Marshal以免踩坑。其实这个问题不止我一个人遇到你可以直接在 issues 中搜到这个问题gopkg.in/yaml.v3 包是由 Canonical 公司Ubuntu 背后的公司为支持其项目 Juju 开发的社区库是 Go 社区目前使用最广泛的 YAML 解析库。但遗憾的是2025 年 4 月 2 日此项目已被作者 Gustavo Niemeyer 标记为不再维护。为此我又特意测试了另一个款处理 YAML 的 Go 包我们一起来看下效果。使用 go-yaml 包处理 YAMLgo-yaml包使用示例如下package main import ( encoding/json fmt log github.com/goccy/go-yaml // YAML 解析库 ) func main() { yamlExample : object: a: 1 1: 2 1: 3 key: value array: - null_value: - boolean: true - integer: 1 // 解析 YAML var data interface{} if err : yaml.Unmarshal([]byte(yamlExample), data); err ! nil { log.Fatalf(YAML parse error: %v, err) } fmt.Printf(Type: %T\nValue: %#v\n, data, data) fmt.Println(--------------------------) // 转换为 JSON jsonData, err : json.Marshal(data) if err ! nil { log.Fatalf(JSON convert error: %v, err) } fmt.Printf(Type: %T\nValue: %s\n, jsonData, jsonData) }可以发现这个包用法与yaml.v3如出一辙我们仅需要修改import语句就可以直接切换到go-yaml包。执行示例代码得到输出如下$ go run goccy-go-yaml/main.go 2025/07/31 23:25:15 YAML parse error: [5:3] mapping key 1 already defined at [4:3] 2 | object: 3 | a: 1 4 | 1: 2 5 | 1: 3 ^ 6 | key: value 7 | array: 8 | - null_value: exit status 1与yaml.v3包一样go-yaml包也无法处理 YAML 文档中同时包含1: 2和1: 3两个键值对的问题。不过这里的报错信息更加清晰一些。现在我们同样注释掉1: 3这个键值对yamlExample : object: a: 1 1: 2 # 1: 3 key: value array: - null_value: - boolean: true - integer: 1 再次执行示例代码得到输出如下$ go run goccy-go-yaml/main.go Type: map[string]interface {} Value: map[string]interface {}{object:map[string]interface {}{1:0x2, a:0x1, array:[]interface {}{map[string]interface {}{null_value:interface {}(nil)}, map[string]interface {}{boolean:true}, map[string]interface {}{integer:0x1}}, key:value}} -------------------------- Type: []uint8 Value: {object:{1:2,a:1,array:[{null_value:null},{boolean:true},{integer:1}],key:value}}我们成功的将 YAML 转换换成了 JSON。可以发现go-yaml包与yaml.v3包用法一致使用go-yaml包的好处是yaml.v3dyno.ConvertMapI2MapS才能完成的事情go-yaml一个包就能够搞定。到这里如何在 Go 语言中操作 YAML to JSON 就讲完了。不过文章还没完我再用 Python 处理一下 YAML to JSON 的场景来解释一下为什么我会在编写 Go 代码的时候疏忽了这个问题。