Home > Backend Development > Golang > How to Handle `json:'omitempty'` with `time.Time` Fields in Go?

How to Handle `json:'omitempty'` with `time.Time` Fields in Go?

Barbara Streisand
Release: 2024-12-30 21:29:14
Original
970 people have browsed it

How to Handle `json:

JSON omitempty with time.Time Field

In Go, the json,omitempty" annotation allows you to exclude fields with empty values from JSON serialization. However, this doesn't work with time.Time fields as they have a zero value that is considered a valid date.

To resolve this issue, set the time.Time field to time.Time{} instead of leaving it as a zero value. This will instruct the JSON encoder to treat the field as empty.

Consider the following example:

package main

import (
    "encoding/json"
    "fmt"
    "time"
)

type MyStruct struct {
    Timestamp time.Time `json:",omitempty"`
    Date      time.Time `json:",omitempty"`
    Field     string    `json:",omitempty"`
}

func main() {
    ms := MyStruct{
        Timestamp: time.Date(2015, 9, 18, 0, 0, 0, 0, time.UTC),
        Date:      time.Time{},
        Field:     "",
    }

    bb, err := json.Marshal(ms)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(bb))
}
Copy after login

Output:

{"Timestamp":"2015-09-18T00:00:00Z"}
Copy after login

Alternatively, you can use a pointer to time.Time and set it to nil to achieve the same effect:

type MyStruct struct {
    Timestamp *time.Time `json:",omitempty"`
    Date      *time.Time `json:",omitempty"`
    Field     string    `json:",omitempty"`
}
Copy after login

The above is the detailed content of How to Handle `json:'omitempty'` with `time.Time` Fields 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