1

When I use ordinary values, for example, a string, the printout works well for me when executing the GET method through POSTMAN. When I want the values in the database to be NULL, and instead of string I use sql.NullString, when executing the GET method in POSTMAN, I get the array of empty objects in JSON format.

While when printing the array in the for loop, the printout is as follows:

{id:1 name:{String:Analytical DBs Valid:true} description:{String: Valid:false} url_icon:{String: Valid:false} url_description:{String: Valid:false}}
{id:2 name:{String:Message brokers Valid:true} description:{String: Valid:false} url_icon:{String: Valid:false} url_description:{String: Valid:false}}
{id:3 name:{String:Data visualisation Valid:true} description:{String: Valid:false} url_icon:{String: Valid:false} url_description:{String: Valid:false}}
{id:4 name:{String:Time series DBs Valid:true} description:{String: Valid:false} url_icon:{String: Valid:false} url_description:{String: Valid:false}}
{id:5 name:{String:Custom apps Valid:true} description:{String: Valid:false} url_icon:{String: Valid:false} url_description:{String: Valid:false}}
{id:6 name:{String:AI/ML modules Valid:true} description:{String: Valid:false} url_icon:{String: Valid:false} url_description:{String: Valid:false}}

I don't know why it doesn't print these structures as JSON regardless of the type..

To print the array, I use the method: c.IndentedJSON(http.StatusOK, categories)

eglease
  • 2,445
  • 11
  • 18
  • 28
  • 2
    `sql.NullString` does not implement `json.Marshaler` so the `encoding/json` package treats it as a normal struct and marshals it as such. `sql.NullString` is intended for `database/sql` not for json/xml/yaml/toml/etc. You need to use your own custom type if you want it to handle both SQL `NULL` and JSON `null`. – mkopriva Jan 16 '23 at 14:06
  • When I try with string I get an error: sql: Scan error on column index 2, name "description": converting NULL to string is unsupported – Josip Žaja Jan 16 '23 at 14:22
  • By custom type I did not mean `string`, I meant something that implements both the `json.Marshaler` interface and the `sql.Scanner` interface. Btw. you *can* use `*string` if you like and it will work for both json and sql, but the Go code will be then "lesser". – mkopriva Jan 16 '23 at 14:54
  • You can also do something like the following: https://stackoverflow.com/a/51961778/965900 – mkopriva Jan 16 '23 at 15:00

0 Answers0