Go - The note on "omitempty"
Takahiro Kudo
Posted on June 25, 2020
json.Marshal
outputs empty json strings if the struct has a Value-type struct marked "omitempty"
So I usually use Ptr-type struct as a struct field.
package main
import (
"encoding/json"
"fmt"
)
type ValueSlice struct {
Values []V `json:"b,omitempty"`
}
type PtrSlice struct {
Values []*V `json:"b,omitempty"`
}
type ValueStruct struct {
Value V `json:"value,omitempty"`
}
type PtrStruct struct {
Value *V `json:"value,omitempty"`
}
type V struct {
Value string `json:"value"`
}
func main() {
v1 := &ValueSlice{}
v2 := &PtrSlice{}
v3 := &ValueStruct{}
v4 := &PtrStruct{}
bv1, _ := json.Marshal(v1)
bv2, _ := json.Marshal(v2)
bv3, _ := json.Marshal(v3)
bv4, _ := json.Marshal(v4)
fmt.Printf("bv1: %v\n", string(bv1))
fmt.Printf("bv2: %v\n", string(bv2))
fmt.Printf("bv3: %v\n", string(bv3))
fmt.Printf("bv4: %v\n", string(bv4))
}
then
bv1: {}
bv2: {}
bv3: {"value":{"value":""}}
bv4: {}
https://play.golang.org/p/7XKphsEayCN
I have just realized that I can use "The Go Playground" today🤣
đź’– đź’Ş đź™… đźš©
Takahiro Kudo
Posted on June 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
githubcopilot AI Innovations at Microsoft Ignite 2024 What You Need to Know (Part 2)
November 29, 2024