我有以下需要转换为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中表示上述jsons的正确方法是什么?
我想在golang程序中阅读这种YAML。为此,我使用的是spf13 / viper库,但是我找不到任何能够解码这个数组对象之王的方法。
2.。)如何使用毒蛇在golang中阅读这种YAML?示例代码会有所帮助。
答案 0 :(得分:1)
代码很难看,但看起来这个库不喜欢嵌套的对象数组。
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"])
}
}
答案 1 :(得分:1)
将YAML解析为JSON的问题是每个项目中有两个空格。它应该是这样的:
---
siteidparam: "lid"
sites:
-
name: "default"
routingmethod:
method: "urlparam"
siteid: "default"
urlpath: "default"
-
name: "csqcentral"
routingmethod:
method: "urlparam"
siteid: "capitolsquare"
urlpath: "csq"
关于您的第二个问题,请在下面找到有关如何实现该问题的简单摘要:
package main
import (
"bytes"
"fmt"
"github.com/spf13/viper"
)
func main() {
viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")
var yamlExample2 = []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.NewBuffer(yamlExample2))
fmt.Println(viper.Get(`sites`))
}