Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YAML Unmarshal map[string]struct

Tags:

yaml

go

I am definitely not getting this. Here is a given yaml file

items:
  - item1:
      one: "some"
      two: "some string"
  - item2:
      one: "some"
      two: "some string"

And a config:

type Item struct {
    one string
    two string
}
type conf struct {
    Items map[string]Item
}

func (c *conf) getConfig(filename string) *conf {

    yamlFile, err := ioutil.ReadFile(filename)
    if err != nil {
        log.Printf("yamlFile.Get err   #%v ", err)
    }
    err = yaml.Unmarshal(yamlFile, &c)
    if err != nil {
        log.Fatalf("Unmarshal: %v", err)
    }

    //c.Items = make(map[string]Items)
    return c
}

I am using gopkg.in/yaml.v2

With this error:

Unmarshal: yaml: unmarshal errors:
  line 6: cannot unmarshal !!seq into map[string]application.Item

Please help me understand what I am doing wrong here. I googled everywhere already. Thanks in advance.

like image 564
user3677173 Avatar asked May 15 '26 09:05

user3677173


2 Answers

First, you need to change your YAML to

  items:
      item1:
        one: "some"
        two: "some string"
      item2:
        one: "some"
        two: "some string"

Then, in your go code

type Config struct {
    Items map[string]Item
}

type Item struct {
    One string
    Two string
}

Then with

fmt.Printf("%+v\n", c.Items)

you will have

map[item1:{One:some Two:some string} item2:{One:some Two:some string}]
like image 129
Oleg Avatar answered May 18 '26 05:05

Oleg


There are multiple problems with your mapping:

  • Item struct members are not exported. You have to export them:
type Item struct {
    One string `yaml:"one"`
    Two string `yaml:"two"`
}
  • Items is an array of map of Items
type conf struct {
    Items []map[string]Item `yaml:"items"`
}
like image 23
Burak Serdar Avatar answered May 18 '26 06:05

Burak Serdar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!