【发布时间】:2018-10-28 13:46:05
【问题描述】:
我有一个 YAML 格式的配置文件,我试图通过 http API 调用将其输出为 JSON。我正在使用gopkg.in/yaml.v2 解组。 Yaml 可以有非字符串键,这意味着 yaml 被解组为 map[interface{}]interface{},Go 的 JSON 编组器不支持。因此,我在解组之前转换为 map[string]interface{}。但我仍然得到:json: unsupported type: map[interface {}]interface" {}。我不明白。变量cfy 不是map[interface{}]interface{}。
import (
"io/ioutil"
"net/http"
"encoding/json"
"gopkg.in/yaml.v2"
)
func GetConfig(w http.ResponseWriter, r *http.Request) {
cfy := make(map[interface{}]interface{})
f, err := ioutil.ReadFile("config/config.yml")
if err != nil {
// error handling
}
if err := yaml.Unmarshal(f, &cfy); err != nil {
// error handling
}
//convert to a type that json.Marshall can digest
cfj := make(map[string]interface{})
for key, value := range cfy {
switch key := key.(type) {
case string:
cfj[key] = value
}
}
j, err := json.Marshal(cfj)
if err != nil {
// errr handling. We get: "json: unsupported type: map[interface {}]interface" {}
}
w.Header().Set("content-type", "application/json")
w.Write(j)
}
【问题讨论】:
-
这个错误是因为你没有进行递归转换,即
value可能仍然是一个map[interface{}]interface{}。有一个existing library, github.com/ghodss/yaml 可能对您有用。 -
完全正确。我刚刚在测试中看到了这一点。你想这样回答吗?