json - 将 JSON 对象数组转换为 YAML

标签 json go yaml viper-go

我有以下需要转换为 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/

相关文章:

javascript - 将值从ajax中的for循环传递到表单字段

c# - 使用SQL返回JSON字符串

go - 当函数采用接口(interface)时将指针传递给字符串?

r - 在 Quarto 书籍模板中将数据从一个 qmd 文件传递​​到另一个文件?

perl - 在 Perl 中 Grep 一个 YAML 文件

javascript - 如何在 HTML 表格中添加编辑和删除选项?

python - 如何将 request.data 转换为 dict?

go - 随着时间的推移而超时。After 并不像使用自动收报机或计时器超时

go - GAE GO 数据存储中最大的数据类型

dictionary - 如何在 salt 中将字典作为函数参数传递