JSON and zero dates in Go

Jean-François Bustarret
Random Go tips
Published in
1 min readOct 24, 2015

The Go JSON encoder is great (easy to use and easy to extend), except for a tiny thing : zero times which marshal to “0001–01–01T00:00:00Z” instead of something like null. Yuck !

enc := json.NewEncoder(os.Stdout)
enc.Encode(time.Time{}) // "0001-01-01T00:00:00Z"

Fortunately, whenever there is a problem in Go, there is a solution using an interface — in our case : json.Marshaler. Let’s define a custom type and implement the interface:

type MyTime struct {
time.Time
}
func (t MyTime) MarshalJSON() ([]byte, error) {
if t.IsZero() {
return []byte("null"), nil
} else {
return t.Time.MarshalJSON()
}
}
enc := json.NewEncoder(os.Stdout)
enc.Encode(MyTime{}) // null
enc.Encode(MyTime{time.Now()}) // "2009-11-10T23:00:00Z"

http://play.golang.org/p/yYrAH5Pw23

Why define a struct and not a type alias ? Because type aliases do no inherit the methods of their base type :

type MyTimeStruct struct {
time.Time
}
// This works, as other time.Time methods
MyTimeStruct{}.IsZero()
type MyTimeAlias time.Time
// This does not compile
MyTimeAlias{}.IsZero()

http://play.golang.org/p/Lhy88NBQs3

--

--