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.

GoData Integrity

Code

gosnippet
37 lines
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

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:`.