Skip to content

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

Description

@adityaladwa

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?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions