英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论