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

Is it possible to omit undefined values? #188

@lesovsky

Description

@lesovsky

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions