DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

2

Go - The note on "omitempty"

#go

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🀣

Top comments (0)

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay