Search code examples
dictionarygoyamlmarshalling

Is it possible to marshal a Go struct while including a map name?


Say that I have a go struct that is set up like this:

type TestStruct struct {
    ID string
    ConfigTest         map[string]Object
    
}

With the object inside having yaml and/or json tags, for marshalling and later saving into a file, like this:

type Object struct {
    ID          string  `yaml:"ID"`
    Value       float64 `yaml:"Value"`
}

So, when I marshal the TestStruct.ConfigTest, and save it to a file using ioutil.WriteFile() I get something like this as the output:

obj1:
    ID: "Hello"
    Value: 1.2
obj2:
    ID: "World"
    Value: 3.4
...(etc)

But what I actually want is to marshal, and save the file like this:

Objects:  
    obj1:
        ID: "Hello"
        Value: 1.2
    obj2:
        ID: "World"
        Value: 3.4
    ...(etc)

Is this possible?


Solution

  • You have two basic choices:

    Reuse TestStruct:

    Change TestStruct to have the appropriate labels on the fields: one to skip marshaling ID, the other to give the desired name to ConfigTest.

    type TestStruct struct {
      ID string                             `yaml:"-"`
      ConfigTest         map[string]Object  `yaml:"Objects"`
    }
    

    Use a wrapper struct:

    If you can't, or don't want to, modify TestStruct (ie: because it's already marshaled somewhere else), you can use a wrapper struct:

    type WrapperStruct struct {
      ConfigTest         map[string]Object  `yaml:"Objects"`
    }
    

    And marshal your new wrapper struct instead of MyStruct.