Golang如何在将结构体编组为YAML时避免在键”on”上使用双引号?

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

Golang how to avoid double quoted on key "on" when marshaling struct to yaml

问题

我有一个简单的结构体,如下所示:

type Foo struct {
    On string `yaml:"on"`
}

我想要将这个结构体以两种方式之一编组成YAML字符串:

  • 方式1:https://go.dev/play/p/Btwt3Gi09ZG
  • 方式2:https://go.dev/play/p/r9jwscnuOAR

但是无论哪种方式,我都得到了相同的结果,在键"on"上有双引号

"on": hello

我该如何避免这种情况?以下是我想要的结果:

on: hello

Go的版本是go1.17.2 darwin/amd64

英文:

I have a simple struct such as:

type Foo struct {
    On string `yaml:"on"`
}

And want to marshal this struct into YAML string in either way

Always get the same result with double-quote on key "on"

"on": hello

How can I avoid this? Following is the result I want

on: hello

The version of go is go1.17.2 darwin/amd64

答案1

得分: 1

那将是无效的YAML1.1(或者至少令人困惑),因为on被解释为布尔值true的关键字(参见YAML1.1规范)。

根据go-yaml文档

yaml包支持大部分YAML 1.2,但为了向后兼容性保留了一些来自1.1的行为。

具体而言,在yaml包的v3版本中:

  • 支持YAML 1.1的布尔值(yes/no,on/off),只要它们被解码为具有类型的布尔值。否则它们将被视为字符串。YAML 1.2中的布尔值只有true/false。

如果你将yaml:"on"更改为其他任何值,比如yaml:"foo",键将不会被引用。

type T struct {
	On  string `yaml:"on"`
	Foo string `yaml:"foo"`
}

func main() {
	t := T{
		On:  "Hello",
		Foo: "world",
	}

	b, _ := yaml.Marshal(&t)
	fmt.Println(string(b))
}

// "on": hello
// foo: world
英文:

That would be invalid YAML1.1 (or at least confusing) because on is keyword interpreted as boolean value true (see YAML1.1 spec).

As per go-yaml documentation:

> The yaml package supports most of YAML 1.2, but preserves some behavior from 1.1 for backwards compatibility.

> Specifically, as of v3 of the yaml package:
> - YAML 1.1 bools (yes/no, on/off) are supported as long as they are being decoded into a typed bool value. Otherwise they behave as a string. Booleans in YAML 1.2 are true/false only.

If you change yaml:"on" to anything else like yaml:"foo" key will not be quoted.

type T struct {
	On  string `yaml:"on"`
	Foo string `yaml:"foo"`
}

func main() {
	t := T{
		On:  "Hello",
		Foo: "world",
	}

	b, _ := yaml.Marshal(&t)
	fmt.Println(string(b))
}

// "on": hello
// foo: world

huangapple
  • 本文由 发表于 2022年1月25日 21:09:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/70849190.html
匿名

发表评论

匿名网友

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

确定