首页 > 其他分享 >Go - Creating JSON Data Streams from Structs

Go - Creating JSON Data Streams from Structs

时间:2023-10-03 12:13:13浏览次数:204  
标签:Creating encoder JSON NewEncoder Encode Streams data struct

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.

 

标签:Creating,encoder,JSON,NewEncoder,Encode,Streams,data,struct
From: https://www.cnblogs.com/zhangzhihui/p/17740940.html

相关文章

  • Go - Creating JSON Data Byte Arrays from Structs
    Problem: YouwanttocreateJSONdatafromastruct.Solution: Createthestructsthenusethejson.Marshalorjson.MarshalIndenttomarshalthedataintoaJSONsliceofbytes. funcmain(){person:=struct{}data,err:=......
  • Go - Parsing JSON Data Streams Into Structs
    Problem: YouwanttoparseJSONdatafromastream.Solution: CreatestructstocontaintheJSONdata.CreateadecoderusingNewDecoderintheencoding/jsonpackage,thencallDecodeonthedecodertodecodedataintothestructs. InthisfirstJSONf......
  • JSON基础
    概述JavaScriptObjectNotation(JavaScript对象表示法)简称JSON是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、C#、Java、JavaScript、Perl、Python等)。这些特性使JSON成为理......
  • 前端JSON.stringify,JSON.parse函数
    JSON.stringify将对象转为JSON字符串;JSON.parse将JSON字符串转为对象;对象:{productId:129}JSON字符串:"{\"productId\":129}"***JSON使用场景***1. localStorage/sessionStorage存储对象  localStorage/sessionStorage只可以存储字符串,当我们想存储对象的时候,需要使用JSON.s......
  • 爬取豆瓣电影,保存到json文件中
    importurllib.requesturl='https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&start=0&limit=20'headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537......
  • Go每日一库之186:sonic(高性能JSON库)
    介绍我们在日常开发中,常常会对JSON进行序列化和反序列化。Golang提供了encoding/json包对JSON进行Marshal/Unmarshal操作。但是在大规模数据场景下,该包的性能和开销确实会有点不够看。在生产环境下,JSON序列化和反序列化会被频繁的使用到。在测试中,CPU使用率接近10%,其中极端情况......
  • Go - Creating Customized Errors
    Problem: Youwanttocreatecustomerrorstocommunicatemoreinformationabouttheerrorencountered.Solution: Createanewstring-basederrororimplementtheerrorinterfacebycreatingastructwithanErrormethodthatreturnsastring. Therea......
  • Mac部署Python语言json模块(Anaconda)
      本文介绍在Mac电脑的Anaconda环境中,配置Python语言中,用以编码、解码、处理JSON数据的json库的方法;在Windows电脑中配置json库的方法也是类似的,大家可以一并参考。  JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式,常用于数据的序列化和传输。而Python中的json库,......
  • 对象转JSON 遇到的BigDecimal 科学计数法的问题,json转化字段单独处理
    问题描述:项目需要发送JSON数据,BigDecimal转成json仍然显示科学计数法,如果使用BigDecimai的toPlainString()需要将数据格式转为String,所以找了一下fastjson的自定义序列化内容,记录一下,以免以后忘记解决方案:方案一:JSONObject.toJSONString(vo,SerializerFeature.WriteBigDecimalA......
  • VScode对于json格式文件允许添加注释设置(永久有 效)
    如果你想让VSCode永久地将所有的.json文件都识别为JSONC,你可以通过修改VSCode的全局设置来实现。以下是具体步骤:在VSCode中按下Ctrl+,来打开设置(或者在菜单中选择"File"->"Preferences"->"Settings")。在搜索框中输入“files.associations”。在"Files:Associations......