dongwan5381
dongwan5381
2017-05-05 18:02

嵌套列表的解组YAML映射

已采纳

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:
%v

", t)
}

Returns

map[thing1:{[] 0}]

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douchengfei3985 douchengfei3985 4年前

    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.

    点赞 评论 复制链接分享

为你推荐