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?
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.