Say I have the following struct
and I want to rename X and Y according to some string variables in my code.
type RenameStruct struct {
X map[string]interface{}
Y []map[string]interface{}
}
What is the best approach to have them Renamed when Encoding to JSON ? The ones I found here in StackOverflow seems to not be applicable to a struct
where one field is an interface{}
ant the other an []interface{}
.
Edit: I used Dave's answer to create a list of the "RenameStruct" this way: play.golang.org/p/hKZQvhJV2iL
You would need to use a custom JSON marshaller, and then have some way of passing in the names you want. The only easy way I can think of would be to do:
type RenameStruct struct {
X map[string]interface{}
Y []map[string]interface{}
xName string
yName string
}
func (r RenameStruct) MarshalJSON() ([]byte, error) {
data := make(map[string]interface{})
data[r.xName] = r.X
data[r.yName] = r.Y
return json.Marshal(data)
}