0
0
GoHow-ToBeginner · 3 min read

How to Use JSON Tags in Go for Struct Field Mapping

In Go, use json tags in struct field declarations to specify how fields are named or handled during JSON encoding and decoding. Place tags in backticks after the field type, like FieldName type `json:"field_name"`, to map Go fields to JSON keys.
📐

Syntax

JSON tags are added to struct fields using backticks ` after the field type. Inside the tag, use json:"name,option" where name is the JSON key and option can control behavior like omitting empty fields.

  • FieldName type `json:"json_key"`: Maps Go field to JSON key.
  • omitempty: Omits the field if it has a zero value.
  • -: Ignores the field during JSON operations.
go
type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age,omitempty"`
    SSN  string `json:"-"`
}
💻

Example

This example shows how to use JSON tags to control the JSON output of a Go struct. The Name field is mapped to name, Age is omitted if zero, and SSN is ignored.

go
package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age,omitempty"`
    SSN  string `json:"-"`
}

func main() {
    p1 := Person{Name: "Alice", Age: 30, SSN: "123-45-6789"}
    p2 := Person{Name: "Bob", Age: 0, SSN: "987-65-4321"}

    json1, _ := json.Marshal(p1)
    json2, _ := json.Marshal(p2)

    fmt.Println(string(json1))
    fmt.Println(string(json2))
}
Output
{"name":"Alice","age":30} {"name":"Bob"}
⚠️

Common Pitfalls

Common mistakes when using JSON tags include:

  • Forgetting to export struct fields (fields must start with uppercase to be encoded).
  • Using incorrect tag syntax (missing quotes or backticks).
  • Not using omitempty when you want to skip zero values.
  • Expecting unexported fields to be marshaled (they are ignored).
go
package main

import (
    "encoding/json"
    "fmt"
)

type Data struct {
    privateField string `json:"private_field"` // won't be marshaled
    PublicField  string `json:"public_field"`
}

func main() {
    d := Data{privateField: "secret", PublicField: "visible"}
    b, _ := json.Marshal(d)
    fmt.Println(string(b))
}
Output
{"public_field":"visible"}
📊

Quick Reference

TagMeaning
`json:"name"`Maps field to JSON key 'name'
`json:"name,omitempty"`Omit field if zero value
`json:"-"`Ignore field in JSON
Exported fieldField name must start uppercase to be included
Unexported fieldIgnored by JSON marshaller

Key Takeaways

Use backticks with `json:"key,option"` after struct fields to control JSON keys.
Only exported fields (starting with uppercase) are included in JSON encoding.
Use `omitempty` to skip fields with zero values during JSON encoding.
Use `-` to completely ignore a field in JSON operations.
Incorrect tag syntax or unexported fields cause fields to be missing in JSON.