title: MarshalJSON without having all objects in memory at once
body: <p>I want to use <code>json.Encoder</code> to encode a large stream of data without loading all of it into memory at once.</p>
  
  <pre><code>// I want to marshal this
  t := struct {
      Foo string
  
      // Bar is a stream of objects 
      // I don't want it all to be in memory at the same time.
      Bar chan string 
  }{
      Foo: "Hello World",
      Bar: make(chan string),
  }
  
  // long stream of data
  go func() {
      for _, x := range []string{"one", "two", "three"} {
          t.Bar &lt;- x
      }
      close(t.Bar)
  }()
  </code></pre>
  
  <p>I thought maybe the json package had this functionality build in, but that's not the case.</p>
  
  <p><a href="http://play.golang.org/p/3uwTdXqv3v" rel="noreferrer">playground</a></p>
  
  <pre><code>// error: json: unsupported type: chan string
  if err := json.NewEncoder(os.Stdout).Encode(&amp;t); err != nil {
      log.Fatal(err)
  }
  </code></pre>
  
  <p>I'm currently just building the json string myself. </p>
  
  <p><a href="http://play.golang.org/p/570DuHHE7i" rel="noreferrer">playground</a></p>
  
  <pre><code>w := os.Stdout
  w.WriteString(`{ "Foo": "` + t.Foo + `", "Bar": [`)
  
  for x := range t.Bar {
      _ = json.NewEncoder(w).Encode(x)
      w.WriteString(`,`)
  }
  
  w.WriteString(`]}`)
  </code></pre>
  
  <p>Is there a better way to do this?</p>
  
  <p>If the <a href="http://golang.org/pkg/encoding/json/#Marshaler" rel="noreferrer">json.Marshaler</a> was like this is would be trivial.</p>
  
  <pre><code>type Marshaler interface {
      MarshalJSON(io.Writer) error
  }
  </code></pre>