英文:
Issues in parsing yaml file in golang
问题
我正在寻找解析简单的 YAML 文件,但是有些地方似乎不对。已经花了足够的时间了。请问有什么帮助吗?
package main
import (
"fmt"
yaml "gopkg.in/yaml.v2"
)
func main() {
raw := `
targets:
- from: "http://localhost:8080/test1"
timeout: "10s"
- from: "http://localhost:8080/test2"
timeout: "30s"
`
type Target struct {
From string `yaml:"from"`
Timeout string `yaml:"timeout"`
}
type Config struct {
Targets []Target `yaml:"targets"`
}
cfg := Config{}
err := yaml.Unmarshal([]byte(raw), &cfg)
if err != nil {
fmt.Println(err)
}
fmt.Println("Config", cfg)
}
我得到了下面的空输出:
Config [{ } { }]
Playground -> https://play.golang.org/p/LANMpq_zPP9
英文:
I am looking for unmarshaling simple yaml but something is not right. Have spent enough time already. Any help please?
package main
import (
"fmt"
yaml "gopkg.in/yaml.v2"
)
func main() {
raw := `
targets:
- from: "http://localhost:8080/test1"
timeout: "10s"
- from: "http://localhost:8080/test2"
timeout: "30s"
`
type Target struct {
from string `yaml:"from"`
timeout string `yaml:"timeout"`
}
type config struct {
Targets []Target `yaml:"targets"`
}
cfg := config{}
err := yaml.Unmarshal([]byte(raw), &cfg)
if err != nil {
fmt.Println(err)
}
fmt.Println("Config", cfg)
}
I am getting below empty o/p
Config {[{ } { }]}
Playground -> https://play.golang.org/p/LANMpq_zPP9
答案1
得分: 1
你必须导出结构体中的字段。根据 API 文档的说明:
只有导出的结构体字段(首字母大写)才会被解组,解组时使用字段名的小写形式作为默认键。
(https://github.com/go-yaml/yaml/blob/496545a6307b/yaml.go#L88)
将你的 Target
结构体修改为:
type Target struct {
From string `yaml:"from"`
Timeout string `yaml:"timeout"`
}
应该可以正常工作。
试一下:https://play.golang.org/p/ZD7Jrv0QBdn
英文:
You have to export the fields in your struct. As stated in the api-documentation:
> Struct fields are only unmarshalled if they are exported (have an upper case first letter), and are unmarshalled using the field name lowercased as the default key.
(https://github.com/go-yaml/yaml/blob/496545a6307b/yaml.go#L88)
Changing your Target
-struct to:
type Target struct {
From string `yaml:"from"`
Timeout string `yaml:"timeout"`
}
should work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论