我有以下需要转换为 YAML 的 json
{
"siteidparam": "lid",
"sites": [
{
"name": "default",
"routingmethod": {
"method": "urlparam",
"siteid": "default",
"urlpath": "default"
}
},
{
"name": "csqcentral",
"routingmethod": {
"method": "urlparam",
"siteid": "capitolsquare",
"urlpath": "csq"
}
}
]
}
我用了online JSON to YAML converter它给出了以下输出,
---
siteidparam: "lid"
sites:
-
name: "default"
routingmethod:
method: "urlparam"
siteid: "default"
urlpath: "default"
-
name: "csqcentral"
routingmethod:
method: "urlparam"
siteid: "capitolsquare"
urlpath: "csq"
当我尝试将生成的相同 YAML 转换回 json 时 from the online service ,它会给出“无法解析”异常。
1.) 在 YAML 中表示上述类型的 json 的正确方法是什么?
我想在我的 golang 程序中读取这种 YAML。为此,我正在使用 spf13/viper 库,但我找不到任何能够解码这个数组对象之王的方法。
2.) 如何使用 viper 在 golang 中读取这种 YAML?示例代码会有所帮助。
最佳答案
代码很丑,但看起来这个库不喜欢对象的嵌套数组。
package main
import (
"bytes"
"fmt"
"github.com/spf13/viper"
)
func main() {
viper.SetConfigType("yaml")
var yamlExample = []byte(`---
siteidparam: "lid"
sites:
-
name: "default"
routingmethod:
method: "urlparam"
siteid: "default"
urlpath: "default"
-
name: "csqcentral"
routingmethod:
method: "urlparam"
siteid: "capitolsquare"
urlpath: "csq"`)
viper.ReadConfig(bytes.NewReader(yamlExample))
fmt.Printf("%s\n", viper.GetString("siteidparam"))
sites := viper.Get("sites").([]interface{})
for i, _ := range sites {
site := sites[i].(map[interface{}]interface{})
fmt.Printf("%s\n", site["name"])
routingmethod := site["routingmethod"].(map[interface{}]interface{})
fmt.Printf(" %s\n", routingmethod["method"])
fmt.Printf(" %s\n", routingmethod["siteid"])
fmt.Printf(" %s\n", routingmethod["urlpath"])
}
}
关于json - 将 JSON 对象数组转换为 YAML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35532732/