gpt4 book ai didi

Golang如何在将结构编码(marshal)到yaml时避免在键 "on"上双引号

转载 作者:行者123 更新时间:2023-12-05 05:48:13 30 4
gpt4 key购买 nike

我有一个简单的结构,例如:

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

并希望以任何一种方式将此结构编码为 YAML 字符串

总是得到相同的结果在键“on”上加双引号

"on": hello

我怎样才能避免这种情况?以下是我想要的结果

on: hello

go的版本是go1.17.2 darwin/amd64

最佳答案

这将是无效的 YAML1.1(或至少令人困惑),因为 on 是被解释为 bool 值 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" 之类的任何其他内容,则不会引用 key 。

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

关于Golang如何在将结构编码(marshal)到yaml时避免在键 "on"上双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70849190/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com