When you use Go's encoding/json package, you can attach tags to struct fields to control JSON encoding and decoding.
Basic syntax
This is how you set a JSON tag on a struct field.
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}With that, JSON conversion produces something like {"name": "Alice", "age": 30}.
Main options
Field name
json:"필드명": sets the field name to use when encoding JSON.GO type Person struct { FullName string `json:"name"` }
omitempty
omitempty: if the field has the type's zero value, it is left out of the JSON result.GO type Person struct { Name string `json:"name"` Age int `json:"age,omitempty"` Address string `json:"address,omitempty"` }For example, if
Ageis 0 orAddressis an empty string, that field is omitted from the JSON.
- (dash)
-: this field is ignored entirely during JSON encoding and decoding.GO type Person struct { Name string `json:"name"` Secret string `json:"-"` }In the code above, the
Secretfield is not included in the JSON result.
string option
string: encodes and decodes values such as numbers or booleans as JSON strings.GO type Number struct { Value int `json:"value,string"` }For example, if
Valueis 123, it appears in the JSON as the string"123".
Using multiple options
You can use more than one option by separating them with commas.
GO type Person struct { Name string `json:"name,omitempty"` }
Things to watch
- Capitalization: Go only encodes and decodes exported fields (those that start with an uppercase letter). Unexported fields (lowercase start) are ignored even if they have a tag.
- Default name conversion: with no tag, the field name is used as the JSON key, except that the first letter is lowercased.
- Struct embedding: embedded structs (anonymous fields) are included in the JSON even without a tag. You can still customize them with a tag if you need to.
Example
The example below uses the options above.
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"` // JSON key "name"
Age int `json:"age,omitempty"` // omitted when the value is 0
Secret string `json:"-"` // not included in the JSON
Score int `json:"score,string"` // encodes the number as a string
}
func main() {
p := Person{
Name: "Alice",
Age: 0,
Secret: "loves chocolate",
Score: 100,
}
data, err := json.Marshal(p)
if err != nil {
panic(err)
}
fmt.Println(string(data))
}The output is
{"name":"Alice","score":"100"}- The
Agefield is 0, so it is omitted because of theomitemptyoption. - The
Secretfield is not included at all because of thejson:"-"option. - The
Scorefield is a number, but it is encoded in the JSON as the string"100".
That is how you can use tag options in Go's encoding/json package to control JSON encoding and decoding in detail.
Comments 0
A nickname and a password are required. The same password edits or deletes the comment later. Comments appear after a review.