title: Marshalling empty map[string]interface{} results in "null" instead of nil
body: <p>I have a problem where Go is inserting "null" into my PostgreSQL database's jsonb columns if I try to do the following, and the structs property (in this case of type map[string]interface{}) is empty:</p>
  
  <pre><code>accessMembers, _ := json.Marshal(c.AccessMembers)
  </code></pre>
  
  <p>Doing a test print it outputs the same as the value which get stored into the database:</p>
  
  <pre><code>fmt.Println(string(accessMembers)) // equals the string "null"
  </code></pre>
  
  <p>The problem is that I need it to be - nil (not a string, but the Golang nil), so when I use it in the Exec function below:</p>
  
  <pre><code>sqlStr := `UPDATE my_table SET access_members=$1 WHERE id=$2;`
  
  _, err := db.Exec(sqlStr, accessMembers, c.Id)
  </code></pre>
  
  <p><strong>It should be the equivalent (which works!!) of doing:</strong></p>
  
  <pre><code>_, err := db.Exec(sqlStr, nil, c.Id)
  </code></pre>
  
  <p>I tried a lot of different workarounds, which I thought had to work, but they didn't.</p>
  
  <p>eg.</p>
  
  <pre><code>var accessMembers []byte
  
  am, _ := json.Marshal(c.AccessMembers)
  
  if string(am) != "null"{
      accessMembers = am
  }
  
  sqlStr := `UPDATE my_table SET access_members=$1 WHERE id=$2;`
  
  _, err := db.Exec(sqlStr, accessMembers, c.Id)
  </code></pre>
  
  <p>Which results in the following error: <em>"pq: invalid input syntax for type json"</em></p>
  
  <p>I can't understand why this is not the same, as explicitly writing nil in the Exec functions parameter, since the []byte clearly must be nil, right?</p>
  
  <p>What am I doing wrong here? Here's how I had hoped it would work: <a href="http://play.golang.org/p/UoLAGfhhRl" rel="nofollow">http://play.golang.org/p/UoLAGfhhRl</a></p>
  
  <p><strong>Answer:</strong></p>
  
  <pre><code>var accessMembers interface{} = nil
  
  if c.AccessMembers != nil {
      j, _ := json.Marshal(c.AccessMembers)
      accessMembers = j
  }
  </code></pre>
  
  <p>Thanks to thwd for providing the solution basically, and for pointing out how the database driver marshals nil differently, suggesting interface{} instead of []byte.</p>
  
  <p>Thanks to DonSeba for reminding me to check if the struct field exists before using resources to marshal, do string conversion and comparison, which ought to be more expensive.</p>