Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to omit undefined values? #188

Open
lesovsky opened this issue Sep 22, 2022 · 1 comment
Open

Is it possible to omit undefined values? #188

lesovsky opened this issue Sep 22, 2022 · 1 comment

Comments

@lesovsky
Copy link

lesovsky commented Sep 22, 2022

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.

@jackc
Copy link
Owner

jackc commented Sep 24, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants