dream8877 2016-02-21 05:39
浏览 915
已采纳

将JSON对象数组转换为YAML

I have the following json which needs to convert to YAML

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

I used online JSON to YAML converter and it gave the following output,

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

when I tried to convert the same generated YAML back to json from the online service, it gives "Unable to parse" exception.

1.) what is the correct way of representing above kind of jsons in YAML?

I want to read this kind of YAML inside my golang program. For that I'm using spf13/viper library, but I couldn't find any method which is able to decode this king of array objects.

2.) How to read this kind of YAML in golang using viper? Sample code would help.

  • 写回答

2条回答 默认 最新

  • dongleiqiao2107 2016-02-21 10:50
    关注

    Code is ugly but looks like this library does not like nested arrays of objects.

    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
    ", viper.GetString("siteidparam"))
    
        sites := viper.Get("sites").([]interface{})
        for i, _ := range sites {
            site := sites[i].(map[interface{}]interface{})
            fmt.Printf("%s
    ", site["name"])
            routingmethod := site["routingmethod"].(map[interface{}]interface{})
            fmt.Printf("  %s
    ", routingmethod["method"])
            fmt.Printf("  %s
    ", routingmethod["siteid"])
            fmt.Printf("  %s
    ", routingmethod["urlpath"])
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换