I have a struct in which I put all excess data into a map[string]interface{}
.
If I unmarshal into the Data
property with an empty variable, I don't want to keep it when marshalling. I basically need interface{}
to have json:",omitempty"
, How do I get that?
type Event struct {
From string `json:"from"`
Data map[string]interface{} `json:"data,omitempty"`
}
The omitempty
is for encoding values, but not for decoding.
You cannot generate a complete empty map in Go. (Empty as in, it does not exists.) If your create a variable / value of a struct it always has its default value.
package main
import "fmt"
func main() {
var m map[string]interface{}
fmt.Printf("%v %d
", m, len(m))
// prints: map[] 0
m = nil
fmt.Printf("%v %d
", m, len(m))
// prints: map[] 0
}
Example: Go Playground.