英文:
How to unmarshal YAML in Go
问题
我在Go语言中很难解析这段YAML代码。我得到的错误是“无法将!!seq解组为map[string][]map[string][]string”。我尝试了各种类型的映射,但都没有成功(例如map[string]string;[]map[string]string等)。
import (
"gopkg.in/yaml.v1"
"io/ioutil"
)
type AppYAML struct {
Runtime string `yaml:"runtime,omitempty"`
Handlers map[string][]map[string][]string `yaml:"handlers,omitempty"`
Env_Variables map[string]string `yaml:"env_variables,omitempty"`
}
func main() {
s := `
runtime: go
handlers:
- url: /.*
runtime: _go_app
secure: always
env_variables:
something: 'test'
`
var a AppYAML
if err = yaml.Unmarshal([]byte(s), &a); err != nil {
log.Error(err)
return
}
}
英文:
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)
import (
"gopkg.in/yaml.v1"
"io/ioutil"
)
type AppYAML struct {
Runtime string `yaml:"runtime,omitempty"`
Handlers map[string][]map[string][]string `yaml:"handlers,omitempty"`
Env_Variables map[string]string `yaml:"env_variables,omitempty"`
}
func main() {
s := `
runtime: go
handlers:
- url: /.*
runtime: _go_app
secure: always
env_variables:
something: 'test'
`
var a AppYAML
if err = yaml.Unmarshal([]byte(s), &a); err != nil {
log.Error(err)
return
}
}
答案1
得分: 9
将类型声明更改为以下内容:
type AppYAML struct {
Runtime string `yaml:"runtime,omitempty"`
Handlers []map[string]string `yaml:"handlers,omitempty"`
Env_Variables map[string]string `yaml:"env_variables,omitempty"`
}
请注意,我已经将引号从yaml:"..."
更改为yaml:"..."
,以使其符合Go语言的语法要求。
英文:
Change type declaration to this:
type AppYAML struct {
Runtime string `yaml:"runtime,omitempty"`
Handlers []map[string]string `yaml:"handlers,omitempty"`
Env_Variables map[string]string `yaml:"env_variables,omitempty"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论