2

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?

18
  • You can't make dynamic columns with in MySQL. Commented Apr 9, 2018 at 11:00
  • There is no way to create dynamic struct with different json tags or hiding the value. Commented Apr 9, 2018 at 11:02
  • @RaymondNijland i was talking on the result that will be shown as a json value , the table have a row called age but it has some null values so i want to control the struct where the age is null it will just show the id and user else it will show all the fields Commented Apr 9, 2018 at 11:04
  • 1
    @Medone you'll have to convert the int to int64 before you use sql.NullInt64. And if you opt for the alternative you can use COALESCE(age, 0) as well. Commented Apr 9, 2018 at 11:37
  • 1
    @Medone use ,omitempty in the json tag if you want to avoid null properties in your json. Commented Apr 9, 2018 at 13:41

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

You can use gonull (https://github.com/lomsa-dev/gonull):

type Users struct {
    ID    gonull.Nullable[int]    `json:"id"`
    Name  gonull.Nullable[string] `json:"name"`
    Age   gonull.Nullable[string] `json:"age,omitempty"`
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.