the result wantedI have a struct in go
type Users struct {
ID int `json:"id"`
Name string `json:"name"`
Age string `json:"age"`
}
I have a mysql database in which some age values are nil so basically to make it dynamic I've been searching for the solution. "Age string json:-
" to hide the field if it is returnig the value nil from mysql. I did two queries
query1: select id,name,age from users where age is not null
query2: select id,name from users where age is null
How can I make it a dynamic query to show the age if exsits else it doesn't don't show it?
Don't do that. Instead, use a nil-able type for your Age
field. *string
or sql.NullString
would be the most natural choices. Then just always select it, and the NULL value will be treated properly.
type Users struct {
ID int `json:"id"`
Name string `json:"name"`
Age *string `json:"age"`
}
Then always use:
SELECT id, name, age FROM users
And when Age
is NULL in the database, it will be nil
in Go, and when it's not NULL in the database, it will be a non-nil pointer to a string in Go.
Use ifnull()
in your query, so that null
values can be fetched as ''
(string's default value)
select id,name,ifnull(age, '') from users;
Then use omitempty
in json
tag of Age field.
type Users struct {
ID int `json:"id"`
Name string `json:"name"`
Age string `json:"age,omitempty"`
}
If default value is fetched in Age, then it will be ignored in json response.