-
Notifications
You must be signed in to change notification settings - Fork 17.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
encoding/json: custom format for time.Duration #4712
Comments
Updated proposed syntax in http://play.golang.org/p/LHuEhLVmTt to matchkey-value encoding used in protobuf struct tags. http://play.golang.org/p/LHuEhLVmTt |
Updated proposed syntax to match key-value encoding used in protobuf package. http://play.golang.org/p/LHuEhLVmTt |
It is unclear to me whether we can do this. Go 1.1 programs would not be able to read the Go 1.2 encoding, although we could make Go 1.2 programs able to read the Go 1.1 encoding. It's not that encoding/json is assuming nanoseconds, it's that it's treating the Duration as a simple int64. Labels changed: added go1.2maybe. |
Rather than applying struct tags, it might be simpler just to use 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. |
This bit me tonight in Go 1.6. It is disappointing to think that we are still clinging to compatibility when it is (in my view) more likely that bugs are being introduced due to the lack of implementation of json.Marshaler. |
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"`
} |
If you want a custom duration marshaling, define a type that implements json.Marshaler/json.Unmarshaler. At this point we're not going to change this fundamental detail of the json package. |
@rsc maybe could be considered for an upcoming major version of Go (2.x) ? |
Everything will be considered anew for any Go 2. |
@bradfitz then can this be labeled as such so it doesn't get lost? Yes, I know right now you can just create a new type then carry the transformation around the whole program wherever needed to use the filed as |
Since it's labeled Thinking, we're good. We'll find it back if/when we think about Go2. |
The idea for supporting custom |
Ideally the conversion process could be exposed, some thing along the line like this. So it's customizable on how to convert one type to another when decoding/encoding. |
The text was updated successfully, but these errors were encountered: