JSON golang boolean omitempty

Use pointers

package main

import (
    "encoding/json"
    "fmt"
)

type SomeStruct struct {
    SomeValue *bool `json:"some_value,omitempty"`
}

func main() {
    t := new(bool)
    f := new(bool)

    *t = true
    *f = false

    s1, _ := json.Marshal(SomeStruct{nil})
    s2, _ := json.Marshal(SomeStruct{t})
    s3, _ := json.Marshal(SomeStruct{f})

    fmt.Println(string(s1))
    fmt.Println(string(s2))
    fmt.Println(string(s3))
}

Output:

{}
{"some_value":true}
{"some_value":false}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)