英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论