How to Decode JSON with Non-Standard Time Formats?

Patricia Arquette
Release: 2024-11-09 08:37:02
Original
670 people have browsed it

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"
}
Copy after login

And a custom struct to hold the data:

type Person struct {
    Name string `json:"name"`
    BirthDate time.Time `json:"birth_date"`
}
Copy after login

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))
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template