encoding/json: custom format for time.Duration

Feature request:

JSON struct tags could be enhanced to provide the notion of time units since the parser
currently assumes everything is ns, causing workarounds of the type that may need to get
fixed, as in https://golang.org/cl/7086059

Sample code: http://play.golang.org/p/CZH9ThvhxK

What is the expected output?
&{Access:12345 Refresh:23456 ExpiresIn:1h0m0s ValidIn:1.234us}
2013-01-21 22:37:40.646947673 -0800 PST
2013-01-21 23:37:40.647083585 -0800 PST

What do you see instead?
&{Access:12345 Refresh:23456 ExpiresIn:3.6us ValidIn:1.234us}
2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00.0000036 +0000 UTC

3 thoughts on “encoding/json: custom format for time.Duration

  1. Rather than applying struct tags, it might be simpler just to use time.ParseDuration(). For example: http://play.golang.org/p/M7b2LZWQPD

    As you’ll notice, in the example, it accepts both strings and ints, which preserves backwards compatibility. Of course, this is lacking implementations of MarshalBinary/Text/etc since it’s merely an example.

  2. I could propose this as an alternative:

    type demo struct {
    	Field  time.Time     `json:"name,omitempty,layout:Mon Jan _2 15:04:05 2006"`
    	Field2 time.Duration `json:"name,omitempty,duration:42s"`
  3. The idea for supporting custom time.Time layout in the struct tags like @dlsniper suggested seems a bit out of scope for the original issue, but would be an incredible improvement IMHO – perhaps it’s worth discussing it in another issue / proposal?

Comments are closed.