"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 Customize the JSON Layout for time.Time Fields in Golang?

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

Published on 2024-11-20
Browse:680

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"}

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

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
}

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:

jt := jsonTime{time.Now(), time.Kitchen}
x := map[string]interface{}{
    "foo": jt,
    "bar": "baz",
}
data, err := json.Marshal(x)
if err != nil {
    panic(err)
}

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

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