Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Parse YAML with arbitrary keys [duplicate]

Tags:

yaml

go

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

like image 519
Stephen D Avatar asked Dec 22 '22 23:12

Stephen D


1 Answers

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}]

like image 76
Mayank Patel Avatar answered Dec 31 '22 05:12

Mayank Patel