Go

struct Tags for JSON Marshaling

admin by @admin ADMIN
8m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Backtick string tags on struct fields control how `encoding/json` serializes them — rename to camelCase, omit zero values, skip entirely. The same tag system is used by many other libraries.
Go
Raw
package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    ID        int    `json:"id"`
    Username  string `json:"username"`
    Email     string `json:"email,omitempty"`        // skip if empty string
    Password  string `json:"-"`                       // never marshal
    CreatedAt string `json:"created_at"`
}

func main() {
    u := User{
        ID:        42,
        Username:  "alice",
        Email:     "",                                // will be omitted
        Password:  "hunter2",                         // never appears in JSON
        CreatedAt: "2025-03-12T14:00:00Z",
    }
    b, _ := json.MarshalIndent(u, "", "  ")
    fmt.Println(string(b))
    // {
    //   "id": 42,
    //   "username": "alice",
    //   "created_at": "2025-03-12T14:00:00Z"
    // }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.