Home > Backend Development > Golang > How to Unmarshal JSON with Incorrect Timezone Offset in Go?

How to Unmarshal JSON with Incorrect Timezone Offset in Go?

Susan Sarandon
Release: 2024-11-05 08:25:02
Original
979 people have browsed it

How to Unmarshal JSON with Incorrect Timezone Offset in Go?

Invalid Datetime Format in JSON Unmarshalling

Background

Go's JSON unmarshaling has issues with datetimes formatted according to ISO8601/RFC3339 that have timezone offsets in the format 0200 instead of 02:00.

Problem

Incorrect JSON Format:

2016-08-08T21:35:14.052975+0200
Copy after login

Expected Correct Format:

2016-08-08T21:35:14.052975+02:00
Copy after login

Possible Cause:

The JSON was generated using C's strftime function with a format string that does not include the colon in the timezone offset.

Solution

To resolve this issue and enable the correct unmarshalling of both formats, a custom time field type can be defined:

<code class="go">type MyTime struct {
    time.Time
}

func (self *MyTime) UnmarshalJSON(b []byte) (err error) {
    s := string(b)

    // Remove double quotes from JSON value
    s = s[1:len(s)-1]

    t, err := time.Parse(time.RFC3339Nano, s)
    if err != nil {
        t, err = time.Parse("2006-01-02T15:04:05.999999999Z0700", s)
    }
    self.Time = t
    return
}</code>
Copy after login

In this custom type, the UnmarshalJSON method attempts to parse the string according to both RFC3339Nano (with a colon in the timezone offset) and a modified version of RFC3339Nano without the colon.

Usage

To use the custom time field type:

<code class="go">type Test struct {
    Time MyTime `json:"time"`
}</code>
Copy after login

This struct can then be unmarshalled from either JSON format with the incorrect or correct timezone offset.

Notes

  • By default, the RFC3339Nano format in time.Parse uses "Z" for the timezone offset, while in the modified format, "Z0700" is used.
  • The year "2006" in the time format is a reference to the first year of Go's release.

The above is the detailed content of How to Unmarshal JSON with Incorrect Timezone Offset in Go?. 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