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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律