JSON Struct Tags With omitempty
Map Go struct fields to JSON keys with tags, drop empty fields via omitempty, and hide internals with the dash tag during round trips.
Code
package main
import (
"encoding/json"
"fmt"
)
type Order struct {
ID string `json:"id"`
AmountCents int `json:"amount_cents"`
Coupon string `json:"coupon,omitempty"`
InternalNote string `json:"-"`
}
func main() {
in := `{"id":"o-1024","amount_cents":4950,"coupon":"WELCOME10"}`
var order Order
if err := json.Unmarshal([]byte(in), &order); err != nil {
fmt.Println("decode error:", err)
return
}
fmt.Printf("decoded: %+v\n", order)
// Marshal 沿用同一份 tag 映射:驼峰字段名输出为 snake_case
out, err := json.Marshal(order)
if err != nil {
fmt.Println("encode error:", err)
return
}
fmt.Println("encoded:", string(out))
// Coupon 置空后被 omitempty 整个省略,InternalNote 始终被 "-" 隐藏
order.Coupon = ""
compact, _ := json.Marshal(order)
fmt.Println("omitempty:", string(compact))
}What the code does
JSON Struct Tags With omitempty comes down to the function main.
err is inspected at 2 call sites before any result is trusted.
Applying it
Running the file prints labeled results such as decode error:, decoded:, encode error: — each operation’s effect is visible in the output.
Statements that set the outcome here
if err != nil {
fmt.Println("encode error:", err)
return
}
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- What does JSON Struct Tags With omitempty print when run?
- Execute the whole file; each printed line is prefixed with a label like `decode error:`, `decoded:`, `encode error:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.