I'm trying to read in a YAML file similar to how I've done in Python. But I can't figure out how to use arbitrary keys. I have the following YAML that I would like to read:
apple:
name: item1
banana:
name: item2
I know how to read in the file, but only using empty interfaces. I'd like to read it in as a map to my Item type.
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
type Item struct {
Name string `yaml:"name"`
}
func main() {
input := `
apple:
name: item1
banana:
name: item2`
m := make(map[interface{}]interface{})
err := yaml.Unmarshal([]byte(input), &m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("%v \n", m)
}
What I'm getting in Stdout:
map[apple:map[name:item1] banana:map[name:item2]]
What I would like to see is:
map[apple:{item1} banana:{item2}]
How can I read my YAML file into a map of Item(s)?
For unmarshaling to work the way you want, you should provide the instruction. In your case if you do not want to name to be in a map provide a struct to unmarshal.
so m := make(map[interface{}]interface{})
should change to m := make(map[string]Item)
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
type Item struct {
Name string `yaml:"name"`
}
func main() {
input := `
apple:
name: item1
banana:
name: item2`
m := make(map[string]Item)
err := yaml.Unmarshal([]byte(input), &m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("%v \n", m)
}
Output: map[apple:{item1} banana:{item2}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With