How to unmarshal YAML in Go

huangapple go评论143阅读模式
英文:

How to unmarshal YAML in Go

问题

我在Go语言中很难解析这段YAML代码。我得到的错误是“无法将!!seq解组为map[string][]map[string][]string”。我尝试了各种类型的映射,但都没有成功(例如map[string]string;[]map[string]string等)。

  1. import (
  2. "gopkg.in/yaml.v1"
  3. "io/ioutil"
  4. )
  5. type AppYAML struct {
  6. Runtime string `yaml:"runtime,omitempty"`
  7. Handlers map[string][]map[string][]string `yaml:"handlers,omitempty"`
  8. Env_Variables map[string]string `yaml:"env_variables,omitempty"`
  9. }
  10. func main() {
  11. s := `
  12. runtime: go
  13. handlers:
  14. - url: /.*
  15. runtime: _go_app
  16. secure: always
  17. env_variables:
  18. something: 'test'
  19. `
  20. var a AppYAML
  21. if err = yaml.Unmarshal([]byte(s), &a); err != nil {
  22. log.Error(err)
  23. return
  24. }
  25. }
英文:

I have a hard time to unmarshal this piece of YAML in Go. The error I'm getting is cannot unmarshal !!seq into map[string][]map[string][]string . I've tried all kind of maps with no success (map[string]string ; []map[string]string and so on)

  1. import (
  2. "gopkg.in/yaml.v1"
  3. "io/ioutil"
  4. )
  5. type AppYAML struct {
  6. Runtime string `yaml:"runtime,omitempty"`
  7. Handlers map[string][]map[string][]string `yaml:"handlers,omitempty"`
  8. Env_Variables map[string]string `yaml:"env_variables,omitempty"`
  9. }
  10. func main() {
  11. s := `
  12. runtime: go
  13. handlers:
  14. - url: /.*
  15. runtime: _go_app
  16. secure: always
  17. env_variables:
  18. something: 'test'
  19. `
  20. var a AppYAML
  21. if err = yaml.Unmarshal([]byte(s), &a); err != nil {
  22. log.Error(err)
  23. return
  24. }
  25. }

答案1

得分: 9

将类型声明更改为以下内容:

  1. type AppYAML struct {
  2. Runtime string `yaml:"runtime,omitempty"`
  3. Handlers []map[string]string `yaml:"handlers,omitempty"`
  4. Env_Variables map[string]string `yaml:"env_variables,omitempty"`
  5. }

请注意,我已经将引号从yaml:"..."更改为yaml:"...",以使其符合Go语言的语法要求。

英文:

Change type declaration to this:

  1. type AppYAML struct {
  2. Runtime string `yaml:"runtime,omitempty"`
  3. Handlers []map[string]string `yaml:"handlers,omitempty"`
  4. Env_Variables map[string]string `yaml:"env_variables,omitempty"`
  5. }

huangapple
  • 本文由 发表于 2015年3月12日 18:17:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/29007036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定