This repository was archived by the owner on Jul 12, 2025. It is now read-only.

Description
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.