Custom MarshalJSON and skipping 0 value

1,701 views
Skip to first unread message

bsr

unread,
Dec 15, 2012, 1:07:43 PM12/15/12
to golan...@googlegroups.com
I wrote a custom MarshalJSON function to format the time the way I wanted. But, it gives error.

 json: error calling MarshalJSON for type Time: unexpected end of JSON input

If I remove

if y := tt.Year(); y == 1 {
return []byte{}, nil
}

it works, but 0 time is outputted as Mon, 01 Jan 0001 00:00:00 UTC

How can I have an empty string if time is 0 value.


func (t Time) MarshalJSON() ([]byte, error) {
tt := time.Time(t)
if y := tt.Year(); y < 0 || y >= 10000 {
return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
}
if y := tt.Year(); y == 1 {
return []byte{}, nil
}

return []byte(tt.Format(`"` + time.RFC1123 + `"`)), nil
}

minux

unread,
Dec 15, 2012, 1:56:01 PM12/15/12
to bsr, golan...@googlegroups.com
On Sun, Dec 16, 2012 at 2:07 AM, bsr <bsr...@gmail.com> wrote:
I wrote a custom MarshalJSON function to format the time the way I wanted. But, it gives error.
FYI, the zero time.Time problem is this issue:

 json: error calling MarshalJSON for type Time: unexpected end of JSON input

If I remove

if y := tt.Year(); y == 1 {
return []byte{}, nil
}

it works, but 0 time is outputted as Mon, 01 Jan 0001 00:00:00 UTC

How can I have an empty string if time is 0 value.


func (t Time) MarshalJSON() ([]byte, error) {
tt := time.Time(t)
if y := tt.Year(); y < 0 || y >= 10000 {
return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
}
if y := tt.Year(); y == 1 {
return []byte{}, nil
}

return []byte(tt.Format(`"` + time.RFC1123 + `"`)), nil
}
json.Marhsaler interface implementation must return valid json object itself, and you
can't use it to skip a zero value (the key for the json dictionary has already been
determined when MarshalJSON is called, and it can't change that, so your best bet
might to to output `""`  http://play.golang.org/p/gyk1yehoTp).

Maybe we can extend the json package to allow MarshalJSON to return a special
error or a nil byte slice to indicate it should omit that field, but I'm not sure.

bsr

unread,
Dec 15, 2012, 2:02:25 PM12/15/12
to golan...@googlegroups.com, bsr
Thank you very much. Your fix would do.

minux

unread,
Dec 15, 2012, 3:17:40 PM12/15/12
to bsr, golan...@googlegroups.com
On Sun, Dec 16, 2012 at 3:02 AM, bsr <bsr...@gmail.com> wrote:
Thank you very much. Your fix would do.
I filed a feature request for a way for custom JSON
marshaler to skip an empty field.

Reply all
Reply to author
Forward
0 new messages