Go - Creating JSON Data Streams from Structs

发布时间 2023-10-03 11:59:29作者: ZhangZhihuiAAA

Problem: You want to create streaming JSON data from structs.


Solution: Create an encoder using NewEncoder in the encoding/json package, passing it an io.Writer . Then call Encode on the encoder to encode structs data to a stream.

 

The io.Writer interface has a Write method that writes bytes to the underlying data stream. You use NewEncoder to create an encoder that wraps around a writer. When you call Encode on the encoder, it will write the JSON struct instance onto the writer.

func   main ()   { 
      encoder   :=   json . NewEncoder ( os . Stdout ) 
      for   i   :=   1 ;   i   <   4 ;   i ++   {   //  we're  just  retrieving  3  records 
          person   :=   struct{}
          encoder . Encode ( person ) 
      } 
}

First, you create an encoder using json.NewEncoder , passing it os.Stdout as the writer. Next, as you loop you get a Person struct instance and pass that to Encode to write to os.Stdout.

If you are annoyed by the untidy output here and wonder if there is an equivalent of MarshalIndent , yes there is. Just set up the encoder with SetIndent like this and you’re good to go:

encoder . SetIndent ( "" ,   "  " )

 

If you have JSON structs coming to you and you either don’t know when it will all come or if you want to write the JSON encodings out first, then you need to use Encode . You can use Marshal only if you have all the JSON data available to you.
And of course, Encode is also faster than Marshal.