go

Go - The note on "omitempty"

takakd

Takahiro Kudo

Posted on June 25, 2020

Go - The note on "omitempty"

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))
}
Enter fullscreen mode Exit fullscreen mode

then

bv1: {}
bv2: {}
bv3: {"value":{"value":""}}
bv4: {}
Enter fullscreen mode Exit fullscreen mode

https://play.golang.org/p/7XKphsEayCN

I have just realized that I can use "The Go Playground" today🤣

đź’– đź’Ş đź™… đźš©
takakd
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