Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How do I tell sqlc to omit a field in the json if it's empty #1132

Unanswered
adityaladwa asked this question in Q&A
Discussion options

Discussed in #1087

Originally posted by adityaladwa July 14, 2021
Let's say I have a table

create table "todos" (
 "id" uuid primary key default uuid_generate_v4(),
 "title" varchar(255) not null,
 "description" text default null
);

After I run sqlc generate the following model will be generated:

type Todo struct {
	ID uuid.UUID `json:"id"`
	Title string `json:"title"`
	Description sql.NullString `json:"description"`
}

I would like to omit the description if it's empty (as it's a nullable column).

Now, I can use column override and use string type instead of sql.NullString. So now the generated type will be

type Todo struct {
	ID uuid.UUID `json:"id"`
	Title string `json:"title"`
	Description string `json:"description"`
}

The problem with this is that if Description is nil, it won't be omitted from the json response. So the response would be something like this:

{
 "id": "c0507d40-de51-451f-b84e-c2f06af7710f",
 "title": "This is a todo",
 "description": null
}

Is there a way I can tell sqlc to add omitempty tag to a particular field? (Description field in this case)

Any other way to solve this issue?

You must be logged in to vote

Replies: 2 comments

Comment options

@adityaladwa do you have a solution now?

You must be logged in to vote
0 replies
Comment options

I have opened a PR for adding support for omitempty

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
Converted from issue

This discussion was converted from issue #1098 on August 17, 2021 16:28.

AltStyle によって変換されたページ (->オリジナル) /