Home > Backend Development > Golang > How to Parse Non-Standard Time Formats from JSON in Golang?

How to Parse Non-Standard Time Formats from JSON in Golang?

Patricia Arquette
Release: 2024-11-09 03:23:01
Original
930 people have browsed it

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

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

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

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!

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