You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have struct with optional field. This optional field is not used sometimes and in such cases marshalling fails with error. Is it possible to omit such fields transparently?
type Person struct {
Name pgtype.Text `db:"name" json:"name"`
Registered pgtype.Bool `db:"registered" json:"registered,omitempty"`
}
func TestExample(t *testing.T) {
c, err := pgx.Connect(context.Background(), "host=127.0.0.1 user=postgres dbname=postgres")
assert.NoError(t, err)
var name pgtype.Text
err = c.QueryRow(context.Background(), "SELECT 'vasya' AS name").Scan(&name)
assert.NoError(t, err)
p := Person{
Name: name,
}
// Here we can define something to 'Registered' field, but it could be unfair or wrong accordingly to "buisiness" logic.
b, err := json.Marshal(&p)
assert.NoError(t, err)
fmt.Println(string(b))
}
omitempty tag not working and test returns:
json: error calling MarshalJSON for type pgtype.Bool: cannot encode status undefined
I would like that could working like with native types:
type Person struct {
Name string `db:"name" json:"name"`
Registered bool `db:"registered" json:"registered,omitempty"`
}
func TestExample(t *testing.T) {
c, err := pgx.Connect(context.Background(), "host=127.0.0.1 user=postgres dbname=postgres")
assert.NoError(t, err)
var name string
err = c.QueryRow(context.Background(), "SELECT 'vasya' AS name").Scan(&name)
assert.NoError(t, err)
p := Person{
Name: name,
}
b, err := json.Marshal(&p)
assert.NoError(t, err)
fmt.Println(string(b))
}
which returns normally with no error and prints {"name":"vasya"} with ommited optional field.
The text was updated successfully, but these errors were encountered:
That seems reasonable, but I don't think it is possible. The MarshalJSON() method defined on the pgtype doesn't have access to the struct tags. And a quick look at the json package docs seems to indicate that omitempty has a hard-coded list of zero values.
I have struct with optional field. This optional field is not used sometimes and in such cases marshalling fails with error. Is it possible to omit such fields transparently?
omitempty
tag not working and test returns:I would like that could working like with native types:
which returns normally with no error and prints
{"name":"vasya"}
with ommited optional field.The text was updated successfully, but these errors were encountered: