Home > Backend Development > Golang > How to Customize the JSON Layout for time.Time Fields in Golang?

How to Customize the JSON Layout for time.Time Fields in Golang?

Susan Sarandon
Release: 2024-11-01 08:42:02
Original
777 people have browsed it

How to Customize the JSON Layout for time.Time Fields in Golang?

Customizing JSON Layout for time.Time in Golang

In Golang, the encoding/json.Marshal function is commonly used to convert objects to JSON. However, under default settings, it may not align with the desired JSON layout. This article illustrates a solution to override the default layout and customize the format used by time.Time fields during JSON marshalling.

Let's assume you have a struct s with a time.Time field named starttime. When marshalling this struct to JSON, you want to use a specific custom layout.

s := {"starttime":time.Now(), "name":"ali"}
Copy after login

To achieve this, we can create a custom type that embeds time.Time and overrides both MarshalText and MarshalJSON methods.

<code class="go">import "fmt"
import "time"
import "encoding/json"

type jsonTime struct {
    time.Time
    f string
}

func (j jsonTime) format() string {
    return j.Time.Format(j.f)
}

func (j jsonTime) MarshalText() ([]byte, error) {
    return []byte(j.format()), nil
}

func (j jsonTime) MarshalJSON() ([]byte, error) {
    return []byte(`"` + j.format() + `"`), nil
}</code>
Copy after login

By overriding MarshalText, we control how the jsonTime type converts its value to a text form, allowing us to specify the custom layout. Additionally, by overriding MarshalJSON, we ensure the overridden method is used instead of the built-in time.Time implementation for JSON marshalling.

With the custom jsonTime type, you can now marshal your s struct using the desired layout:

<code class="go">jt := jsonTime{time.Now(), time.Kitchen}
x := map[string]interface{}{
    "foo": jt,
    "bar": "baz",
}
data, err := json.Marshal(x)
if err != nil {
    panic(err)
}</code>
Copy after login

This will produce a JSON string with the starttime field formatted according to the time.Kitchen layout.

The above is the detailed content of How to Customize the JSON Layout for time.Time Fields 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