解析嵌套有列表的YAML映射

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

Unmarshal YAML Map Nested With List

问题

我正在尝试为既是整数又是字符串列表的数据结构编写YAML。但是我在使数据结构和YAML字符串匹配方面遇到了问题。例如:

package main

import (
	"fmt"
	"log"

	yaml "gopkg.in/yaml.v2"
)

type ThingAndGroups struct {
	Groups []string
	Value  int
}

var someStr = `
thing1:
  Groups:
    - g1
    - g2
  Value:
    5
`

func main() {
	t := make(map[string]ThingAndGroups)

	err := yaml.Unmarshal([]byte(someStr), &t)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	fmt.Printf("--- t:\n%v\n\n", t)
}

返回结果为:

map[thing1:{[] 0}]

如何将thing1设置为字符串列表?

英文:

I'm trying to write YAML for a datastructure which is both an int and a list of strings. But I'm having trouble getting the data structure and the YAML string to match. eg

package main

import (
	"fmt"
	"log"

	yaml "gopkg.in/yaml.v2"
)

type ThingAndGroups struct {
	Groups []string
	Value  int
}

var someStr = `
thing1:
  Groups:
    - g1
    - g2
  Value:
    5
`

func main() {
	t := make(map[string]ThingAndGroups)

	err := yaml.Unmarshal([]byte(someStr), &t)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	fmt.Printf("--- t:\n%v\n\n", t)
}

Returns

> map[thing1:{[] 0}]

How do I get thing1 to be a list of strings?

答案1

得分: 5

将你的类型更改为以下内容:

type ThingAndGroups struct {
    Groups []string `yaml:"Groups"`
    Value  int      `yaml:"Value"`
}

https://godoc.org/gopkg.in/yaml.v2#Marshal 的文档中提到:

只有导出的结构字段(首字母大写)才会被解组,解组时使用字段名的小写形式作为默认键。可以通过字段标签中的 "yaml" 名称定义自定义键。

或者,你可以将你的 YAML 输入更改为使用小写字段,如 value,这样你就不需要指定自定义名称了。

英文:

Change your type to this

type ThingAndGroups struct {
	Groups []string `yaml:"Groups"`
	Value  int      `yaml:"Value"`
}

In the doc for https://godoc.org/gopkg.in/yaml.v2#Marshal it says

> 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. Custom keys may be defined via the "yaml" name in the field tag

Alternatively you could change your yaml input to use lowercase fields like value then you wouldn't need to specify custom names.

huangapple
  • 本文由 发表于 2017年5月6日 02:02:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/43811221.html
匿名

发表评论

匿名网友

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

确定