【发布时间】:2022-01-25 13:09:42
【问题描述】:
我有一个简单的结构,例如:
type Foo struct {
On string `yaml:"on"`
}
并希望以任何一种方式将此结构编组为 YAML 字符串
总是得到相同的结果在键“on”上加双引号
"on": hello
我怎样才能避免这种情况?以下是我想要的结果
on: hello
go的版本是go1.17.2 darwin/amd64
【问题讨论】:
我有一个简单的结构,例如:
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-yamldocumentation:
yaml 包支持 YAML 1.2 的大部分内容,但保留了 1.1 中的一些行为以实现向后兼容性。
具体来说,从 yaml 包的 v3 开始:
- 只要将 YAML 1.1 布尔值(是/否、开/关)解码为类型化的布尔值,它们就受支持。否则,它们表现为字符串。 YAML 1.2 中的布尔值仅是真/假。
如果您将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
【讨论】: