问题:使用结构体数组进行YAML编组时出现问题。

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

Issue Marshaling YAML with an array of struct

问题

我期望生成的yaml文件中包含作为空对象写入的servers数组。我该如何修复这个问题,以便将servers数组写入yaml文件中?

代码:

package configwritter

import (
	"fmt"
	"io/ioutil"
	"log"

	"gopkg.in/yaml.v2" //go get gopkg.in/yaml.v2
)

type Server struct {
	name string `yaml:"name"`
	ip   string `yaml:"ip"`
}

type Confugration struct {
	Name    string
	Servers []Server
}

func WriteConfig() {
	config := Confugration{
		Name: "Test",
		Servers: []Server{
			{"server1", "10.0.0.100"},
			{"server1", "10.0.0.101"},
		},
	}

	data, err := yaml.Marshal(&config)
	if err != nil {
		log.Fatal(err)
	}

	err2 := ioutil.WriteFile("config.yaml", data, 0)
	if err2 != nil {
		log.Fatal(err2)
	}

	fmt.Println("data written")
}

输出:

name: Test
servers:
- {}
- {}

你需要将Server结构体中的字段名首字母大写,以便在序列化为yaml时能够访问到它们。将name改为Name,将ip改为IP。修改后的代码如下:

type Server struct {
	Name string `yaml:"name"`
	IP   string `yaml:"ip"`
}

这样修改后,生成的yaml文件将包含正确的服务器信息。

英文:

I am expecting the resulting yaml file to contain the servers array which are being written as empty objects. How could i go about fixing this so that the servers array is written to the yaml file?

Code:

package configwritter

import (
	"fmt"
	"io/ioutil"
	"log"

	"gopkg.in/yaml.v2" //go get gopkg.in/yaml.v2
)

type Server struct {
	name string `yaml:"name"`
	ip   string `yaml:"ip"`
}

type Confugration struct {
	Name    string
	Servers []Server
}

func WriteConfig() {
	config := Confugration{
		Name: "Test",
		Servers: []Server{
			{"server1", "10.0.0.100"},
			{"server1", "10.0.0.101"},
		},
	}

	data, err := yaml.Marshal(&config)
	if err != nil {
		log.Fatal(err)
	}

	err2 := ioutil.WriteFile("config.yaml", data, 0)
	if err2 != nil {
		log.Fatal(err2)
	}

	fmt.Println("data written")
}

Output:

name: Test
servers:
- {}
- {}

答案1

得分: 2

似乎你的Server结构体上的字段需要是公开的,这样yaml模块才能读取它们。

根据Marshal文档

> 只有导出的结构体字段(首字母大写)才会被编组。

你可以通过更改Server的类型定义来解决这个问题,使字段变为导出的(首字母大写),像这样:

type Server struct {
	Name string `yaml:"name"`
	IP   string `yaml:"ip"`
}

生成的config.yaml文件如下:

name: Test
servers:
- name: server1
  ip: 10.0.0.100
- name: server1
  ip: 10.0.0.101
英文:

It seems the fields on your Server struct need to be public in order for the yaml module to read them.

From the Marshal documentation:

> Struct fields are only marshalled if they are exported (have an upper case first letter)

You can fix this by changing the type definition for Server so that the fields are exported (have capitalized names), like so:

type Server struct {
	Name string `yaml:"name"`
	IP   string `yaml:"ip"`
}

With output config.yaml file:

name: Test
servers:
- name: server1
  ip: 10.0.0.100
- name: server1
  ip: 10.0.0.101

huangapple
  • 本文由 发表于 2021年11月18日 08:35:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/70013213.html
匿名

发表评论

匿名网友

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

确定