Home  >  Article  >  Backend Development  >  How to Decode JSON with Non-Standard Time Formats?

How to Decode JSON with Non-Standard Time Formats?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-09 08:37:02682browse

How to Decode JSON with Non-Standard Time Formats?

Custom Unmarshal for Non-Standard JSON Time Format

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn