title: golang json marshal: how to omit empty nested struct
body: <p><a href="https://play.golang.org/p/sA0D6pHZnc" rel="noreferrer">go playground</a></p>
  
  <p>As shown in the code above, one can use <code>json:",omitempty"</code> to omit certain fields in a struct to appear in json. </p>
  
  <p>For example</p>
  
  <pre><code>type ColorGroup struct {
      ID     int `json:",omitempty"`
      Name   string
      Colors []string
  }
  type Total struct {
      A ColorGroup`json:",omitempty"`
      B string`json:",omitempty"`
  }
  group := Total{
         A: ColorGroup{},
  
  }
  </code></pre>
  
  <p>In this case, <code>B</code> won't show up in <code>json.Marshal(group)</code></p>
  
  <p>However, if</p>
  
  <pre><code>group := Total{
         B:"abc",
  
  }
  </code></pre>
  
  <p><code>A</code> still shows up in <code>json.Marshal(group)</code></p>
  
  <pre><code>{"A":{"Name":"","Colors":null},"B":"abc"}
  </code></pre>
  
  <p>Question is how do we get only</p>
  
  <pre><code>{"B":"abc"}
  </code></pre>
  
  <p>EDIT:
  After some googling, here is a suggestion <a href="https://stackoverflow.com/questions/18088294/how-to-not-marshal-an-empty-struct-into-json-with-go">use pointer</a>, in other words, turn <code>Total</code> into</p>
  
  <pre><code>type Total struct {
      A *ColorGroup`json:",omitempty"`
      B string`json:",omitempty"`
  }
  </code></pre>