"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Parse Non-Standard Time Formats from JSON in Golang?

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

Published on 2024-11-09
Browse:818

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3