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🀣

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post β†’

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

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

Okay