How to unmarshal YAML in Go

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

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"`
}

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:

确定