将JSON对象数组转换为YAML格式。

huangapple go评论103阅读模式
英文:

Converting JSON object array to YAML

问题

我有以下需要转换为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)如何正确表示这种类型的JSON在YAML中?

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

2)如何在Golang中使用viper读取这种类型的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.

答案1

得分: 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"])
	}
}
英文:

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\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"])
	}
}

答案2

得分: 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") // 或 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`))
}
英文:

The issue with parsing your YAML to JSON is that it has two spaces in each items. It should be like this:

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

About your second question find below a simple snippet about how to achive that:

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`))
}

答案3

得分: 0

yq可以用于在JSON和YAML之间进行转换。

将JSON转换为YAML:

yq -o yaml --prettyPrint
siteidparam: lid
sites:
  - name: default
    routingmethod:
      method: urlparam
      siteid: default
      urlpath: default
  - name: csqcentral
    routingmethod:
      method: urlparam
      siteid: capitolsquare
      urlpath: csq

将YAML转换回JSON:

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

(也可以使用yq转换XML和属性文件)

英文:

yq can be used to convert between JSON and YAML

Convert JSON to YAML

yq -o yaml --prettyPrint
siteidparam: lid
sites:
  - name: default
    routingmethod:
      method: urlparam
      siteid: default
      urlpath: default
  - name: csqcentral
    routingmethod:
      method: urlparam
      siteid: capitolsquare
      urlpath: csq

Convert YAML back to JSON

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

(XML and property files can also be transformed using yq)

huangapple
  • 本文由 发表于 2016年2月21日 13:39:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/35532732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定