Home >Backend Development >Golang >How to Parse Non-Standard Time Formats from JSON in Golang?
Parsing Non-Standard Time Format from JSON
When decoding JSON data into a custom structure, inconsistencies in date formats can arise. To address this, Golang provides the option of implementing custom marshal and unmarshal functions.
Custom Marshaler and Unmarshaler Functions
To specify a custom parsing format, a type alias is created for the time field, and the Marshaler and Unmarshaler interfaces are implemented as follows:
type JsonBirthDate time.Time // UnmarshalJSON translates a JSON string to a time value. func (j *JsonBirthDate) UnmarshalJSON(b []byte) error { s := strings.Trim(string(b), `"`) t, err := time.Parse("2006-01-02", s) if err != nil { return err } *j = JsonBirthDate(t) return nil } // MarshalJSON converts a time value to a JSON string. func (j JsonBirthDate) MarshalJSON() ([]byte, error) { return json.Marshal(time.Time(j)) }
This custom logic checks if the JSON value is in the desired format and parses it accordingly.
Updated Structure and Parsing
The struct is updated to use the custom type, and decoding can proceed as usual:
type Person struct { Name string `json:"name"` BirthDate JsonBirthDate `json:"birth_date"` } decoder := json.NewDecoder(req.Body) if err := decoder.Decode(&person); err != nil { log.Println(err) }
Additional Features
For convenience, a Format method can be added to provide a formatted representation of the date:
// Format prints the date using the specified format string. func (j JsonBirthDate) Format(s string) string { t := time.Time(j) return t.Format(s) }
This custom marshaling and unmarshaling approach allows for flexible parsing of time values from JSON even when they deviate from standard formats.
The above is the detailed content of How to Parse Non-Standard Time Formats from JSON in Golang?. For more information, please follow other related articles on the PHP Chinese website!