For some reason mgo
inserts the empty struct into the db as null value even though I've set omitempty option.
package main
import (
"fmt"
"encoding/json"
)
type A struct {
A bool
}
type B struct {
X int `json:"x,omitempty" bson:"x,omitempty"`
SomeA *A `json:"a,omitempty" bson:"a,omitempty"`
}
func main() {
b := B{}
b.X = 123
if buf, err := json.MarshalIndent(&b, "", " "); err != nil {
fmt.Println(err)
} else {
fmt.Println(string(buf))
}
}
The json encoder leaves out the SomeA
property but in the database it's there as "a" : null
. Am I doing something wrong, or it's simply not possible to do it this way?
Yeah, so problem was having tabs between the json and bson encoder options, that's why omitempty didn't work. So this is wrong:
SomeA *A `json:"a,omitempty" bson:"a,omitempty"`
Instead just have a single space and it's all good:
SomeA *A `json:"a,omitempty" bson:"a,omitempty"`