title: How do you marshal a sql.NullString such that the output is flattened to give just the value in go?
body: <p>Given a go struct</p>
  
  <pre><code>type Company struct {
      ID   int             `json:"id"`              
      Abn  sql.NullString  `json:"abn,string"`
  }
  </code></pre>
  
  <p>when marshalled with something like this</p>
  
  <pre><code>company := &amp;Company{}
  company.ID = 68
  company.Abn = "SomeABN"
  result, err := json.Marshal(company)
  </code></pre>
  
  <p>the result is</p>
  
  <pre><code>{
      "id": "68",
      "abn": {
          "String": "SomeABN",
          "Valid": true
      }
  }
  </code></pre>
  
  <p>The result desired is </p>
  
  <pre><code>{
      "id": "68",
      "abn": "SomeABN"
  }
  </code></pre>
  
  <p>I've tried explicitly stating that Abn is a string.</p>
  
  <pre><code>Abn  sql.NullString  `json:"abn,string"`
  </code></pre>
  
  <p>which did not change the result.</p>
  
  <p>How do you marshal a sql.NullString such that the output is flattened to give just the value in go?</p>
  
  <p>EDIT</p>
  
  <p>Something like I ended up with after reading the answers from <a href="https://stackoverflow.com/users/8256506/nilsocket">https://stackoverflow.com/users/8256506/nilsocket</a> and <a href="https://stackoverflow.com/users/965900/mkopriva">https://stackoverflow.com/users/965900/mkopriva</a></p>
  
  <pre><code>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"`         
  }
  </code></pre>