encoding/json: empty time.Time serialized even though omitempty is specified

320 views
Skip to first unread message

Ondřej Kupka

unread,
Sep 9, 2014, 8:24:38 AM9/9/14
to golan...@googlegroups.com
Hi,

I basically have a struct looking like

type Foobar struct {
    t time.Time `json:"omitempty"`
}

Now when I do

var fb Foobar

and then try to serialize it, I get "t":"0001-01-01T00:00:00Z" instead of "t" being absent.

So I am just wondering it if makes sense to expect this to work or not.
time.Time implements the JSON interfaces, so I was expecting this to work.

Cheers,
Ondrej

Denis Bakhtin

unread,
Sep 9, 2014, 8:43:20 AM9/9/14
to Ondřej Kupka, golan...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Nate Brennand

unread,
Sep 9, 2014, 9:42:45 AM9/9/14
to Denis Bakhtin, Ondřej Kupka, golan...@googlegroups.com

@Denis, in your playground link you don’t make the attribute T exposed. The attribute must be exposed for the field to ever be marshaled into JSON. Also, omitempty must be used after a comma to denote that it’s a property, not the name of the field.
Here’s an updated example: http://play.golang.org/p/Jour5HAKEe

Your best bet seems to be making the T attribute a pointer, it will be nil when uninstantiated.
http://play.golang.org/p/ud6OLZUrmY

Denis Bakhtin

unread,
Sep 9, 2014, 9:53:11 AM9/9/14
to Nate Brennand, Ondřej Kupka, golan...@googlegroups.com
@Nate, right you are, was inattentive :) thank you.

Ian Davis

unread,
Sep 9, 2014, 10:16:30 AM9/9/14
to golan...@googlegroups.com
 
On Tue, Sep 9, 2014, at 01:24 PM, Ondřej Kupka wrote:
and then try to serialize it, I get "t":"0001-01-01T00:00:00Z" instead of "t" being absent.
 
Reply all
Reply to author
Forward
0 new messages