Home > Article > Backend Development > How to Decode JSON with Non-Standard Time Formats?
To decode JSON with non-standard time formats into custom structs, built-in marshal and unmarshal functions provide flexibility.
Consider the following JSON:
{ "name": "John", "birth_date": "1996-10-07" }
And a custom struct to hold the data:
type Person struct { Name string `json:"name"` BirthDate time.Time `json:"birth_date"` }
Decoding this JSON using the default decoder fails due to the non-standard time format. To handle this, implement custom marshal and unmarshal functions:
type JsonBirthDate time.Time 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 } func (j JsonBirthDate) MarshalJSON() ([]byte, error) { return json.Marshal(time.Time(j)) }
By adding JsonBirthDate to the Person struct and implementing these functions, the following code will decode the JSON correctly:
person := Person{} decoder := json.NewDecoder(req.Body) err := decoder.Decode(&person) if err != nil { log.Println(err) } // person.BirthDate now contains the parsed time as a time.Time object
The above is the detailed content of How to Decode JSON with Non-Standard Time Formats?. For more information, please follow other related articles on the PHP Chinese website!