0

我有以下需要转换为 YAML 的 json

{
  "siteidparam": "lid",
  "sites": [
    {
      "name": "default",
      "routingmethod": {
        "method": "urlparam",
        "siteid": "default",
        "urlpath": "default"
      }
    },
    {
      "name": "csqcentral",
      "routingmethod": {
        "method": "urlparam",
        "siteid": "capitolsquare",
        "urlpath": "csq"
      }
    }
  ]
}

我使用在线 JSON 到 YAML 转换器,它给出了以下输出,

---
  siteidparam: "lid"
  sites: 
    - 
      name: "default"
      routingmethod: 
        method: "urlparam"
        siteid: "default"
        urlpath: "default"
    - 
      name: "csqcentral"
      routingmethod: 
        method: "urlparam"
        siteid: "capitolsquare"
        urlpath: "csq"

当我尝试将相同的生成 YAML从在线服务转换回 json时,它会给出“无法解析”异常。

1.) 在 YAML 中表示上述类型的 json 的正确方法是什么?

我想在我的 golang 程序中阅读这种 YAML。为此,我正在使用 spf13/viper 库,但我找不到任何能够解码这个数组对象之王的方法。

2.) 如何使用 viper 在 golang 中读取这种 YAML?示例代码会有所帮助。

4

2 回答 2

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"])
    }
}
于 2016-02-21T10:50:44.890 回答
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`))
}
于 2016-02-21T10:52:19.213 回答