How do you marshal a sql.NullString such that the output is flattened to give just the value in go?


Given a go struct

type Company struct { ID int `json:"id"` Abn sql.NullString `json:"abn,string"` }

when marshalled with something like this

company := &Company{} company.ID = 68 company.Abn = "SomeABN" result, err := json.Marshal(company)

the result is

{ "id": "68", "abn": { "String": "SomeABN", "Valid": true } }

The result desired is

{ "id": "68", "abn": "SomeABN" }

I've tried explicitly stating that Abn is a string.

Abn sql.NullString `json:"abn,string"`

which did not change the result.

How do you marshal a sql.NullString such that the output is flattened to give just the value in go?


Something like I ended up with after reading the answers from https://stackoverflow.com/users/8256506/nilsocket and https://stackoverflow.com/users/965900/mkopriva

package main import ( "database/sql" "encoding/json" "reflect" //"github.com/lib/pq" ) /* https://medium.com/aubergine-solutions/how-i-handled-null-possible-values-from-database-rows-in-golang-521fb0ee267 */ type NullString sql.NullString func (x *NullString) MarshalJSON() ([]byte, error) { if !x.Valid { x.Valid = true x.String = "" //return []byte("null"), nil } return json.Marshal(x.String) } // Scan implements the Scanner interface for NullString func (ns *NullString) Scan(value interface{}) error { var s sql.NullString if err := s.Scan(value); err != nil { return err } // if nil then make Valid false if reflect.TypeOf(value) == nil { *ns = NullString{s.String, false} } else { *ns = NullString{s.String, true} } return nil } type Company struct { ID int `json:"id"` Abn NullString `json:"abn"` }

Here is the code,

package main import ( "database/sql" "encoding/json" "fmt" "log" ) //Company details type Company struct { ID int `json:"id"` Abn NullString `json:"abn"` } //NullString is a wrapper around sql.NullString type NullString sql.NullString //MarshalJSON method is called by json.Marshal, //whenever it is of type NullString func (x *NullString) MarshalJSON() ([]byte, error) { if !x.Valid { return []byte("null"), nil } return json.Marshal(x.String) } func main() { company := &Company{} company.ID = 68 //create new NullString value nStr := sql.NullString{String: "hello", Valid: true} //cast it company.Abn = NullString(nStr) result, err := json.Marshal(company) if err != nil { log.Println(err) } fmt.Println(string(result)) }

Here is the blog post which explains it in detail.


You cannot, at least not using just sql.NullString and encoding/json.

What you can do is to declare a custom type that embeds sql.NullString and have that custom type implement the json.Marshaler interface.

type MyNullString struct { sql.NullString } func (s MyNullString) MarshalJSON() ([]byte, error) { if s.Valid { return json.Marshal(s.String) } return []byte(`null`), nil } type Company struct { ID int `json:"id"` Abn MyNullString `json:"abn,string"` }




  • JMeter response time vs threads graph - data point
  • Heroku Ruby version won't upgrade?
  • How do I integrate Microsoft health bot to web application
  • Redirecting the print output to a .txt file in Python
  • Unable to select a space or join an organization on run.pivotal.io
  • Allow QGraphicsView to move outside scene
  • How to warn user not to leave the page? [duplicate]
  • Html Multiple Input Elements With Same Name
  • 3 transitions, pausetime between transitions
  • Retrieve 3rd MAX salary in Hive
  • JavaFX Embed Custom Font Not Working
  • Ways of filling 10 places with number from [1..10] such that digit at ith place has value atmost 1 m
  • SyntaxError: expected expression, got '.'
  • Corda: How to implement hierarchical relationships between state data persisted to H2
  • “proxy_pass” cannot have URI part in location given by regular expression
  • Tensorflow crash using tf.train.Saver() with GPU
  • Bundling python(“.py”)files along with java class files for a web application
  • UIScrollView does not restore properly
  • Get name of days between two date in ios?
  • How to find angle formed by the blades of a wind turbine with respect to a horizontal imaginary axis
  • Why do you need 2 Javascript files for cross-platform Cordova plugin?
  • Debugging php script timeout?
  • Does hibernate load two seprate copies of same instance if they are loaded twice from database?
  • Create an Office365 mailbox from within C# Web API method
  • Java Collections.shuffle() weird behaviour [closed]
  • How to use AJAX to upload large CSV file? [closed]
  • Separating definition/instantiation of template classes without 'extern'
  • Possible to set default CloudKit container not based on application name?
  • concise way of flattening multiindex columns
  • gnuplot - How to make zmin equal to zmax keeeping autoscale on z axis
  • r - input value by user to dataframe via shiny
  • Unable to create Access token grant type in wso2 API manager store to test API
  • DataTables move rows between tables
  • Change cell value based on cell color in google spreadsheet
  • Another “Cannot make static reference…” Question
  • calling IO Operations from thread in ruby c extension will cause ruby to hang
  • How to call different template for different category archive page in woocommerce
  • Jersey serializes character value to ASCII equivalent numeric string
  • Angular FormGroup won't update it's value immediately after patchValue or setValue
  • media foundation H264 decoder not working properly