Golang 在将结构编组为 yaml 时如何避免在键 "on" 上双引号
Golang how to avoid double quoted on key "on" when marshaling struct to yaml
我有一个简单的结构,例如:
type Foo struct {
On string `yaml:"on"`
}
并希望以任一方式将此结构编组为 YAML 字符串
总是得到相同的结果在键“on”上加双引号
"on": hello
我怎样才能避免这种情况?以下是我想要的结果
on: hello
go的版本是go1.17.2 darwin/amd64
这将是无效的 YAML1.1(或至少令人困惑),因为 on
是关键字解释为布尔值 true
(参见 YAML1.1 spec)。
根据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.
如果您将 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
我有一个简单的结构,例如:
type Foo struct {
On string `yaml:"on"`
}
并希望以任一方式将此结构编组为 YAML 字符串
总是得到相同的结果在键“on”上加双引号
"on": hello
我怎样才能避免这种情况?以下是我想要的结果
on: hello
go的版本是go1.17.2 darwin/amd64
这将是无效的 YAML1.1(或至少令人困惑),因为 on
是关键字解释为布尔值 true
(参见 YAML1.1 spec)。
根据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.
如果您将 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