Home > Software engineering >  Issue Marshaling YAML with an array of struct
Issue Marshaling YAML with an array of struct

Time:11-18

I am expecting the resulting yaml file to contain the servers array which are being written as empty objects. How could i go about fixing this so that the servers array is written to the yaml file?

Code:

package configwritter

import (
    "fmt"
    "io/ioutil"
    "log"

    "gopkg.in/yaml.v2" //go get gopkg.in/yaml.v2
)

type Server struct {
    name string `yaml:"name"`
    ip   string `yaml:"ip"`
}

type Confugration struct {
    Name    string
    Servers []Server
}

func WriteConfig() {
    config := Confugration{
        Name: "Test",
        Servers: []Server{
            {"server1", "10.0.0.100"},
            {"server1", "10.0.0.101"},
        },
    }

    data, err := yaml.Marshal(&config)
    if err != nil {
        log.Fatal(err)
    }

    err2 := ioutil.WriteFile("config.yaml", data, 0)
    if err2 != nil {
        log.Fatal(err2)
    }

    fmt.Println("data written")
}

Output:

name: Test
servers:
- {}
- {}

CodePudding user response:

It seems the fields on your Server struct need to be public in order for the yaml module to read them.

From the Marshal documentation:

Struct fields are only marshalled if they are exported (have an upper case first letter)

You can fix this by changing the type definition for Server so that the fields are exported (have capitalized names), like so:

type Server struct {
    Name string `yaml:"name"`
    IP   string `yaml:"ip"`
}

With output config.yaml file:

name: Test
servers:
- name: server1
  ip: 10.0.0.100
- name: server1
  ip: 10.0.0.101
  • Related