json

json tag

  • struct tag : field要大寫開頭,tag各有其功用

+// Field appears in JSON as key "myName" 
+ and the field is omitted from the object if its value is empty,
NickName string `json:"nick_name,omitempty"` 
+//Field appears in JSON as key "Field" (大寫), but the field is skipped if empty.
Address string `json:",omitempty"` 
+// Field is ignored by this package.
A string `json:"-"` 
+// Field appears in JSON as key "-".
B string `json:"-,"` 
+//將輸出轉為string
AgeString int64 `json:"AgeString,string"` 

json Marshel

  • 返回 v 的 JSON 编码

  • supported type See [json/encode]

  • 將struct 轉成 json string

  • Marshel如果字串含有HTML特殊字元會被轉換,如果不想要被轉換需要自己將EscapeHTML設為false

[線上範例](https://go.dev/play/p/GL8zgnPMKpv)

json.Unmarshal

  • 將json string轉為struct,需了解傳送過來json的結構, 利用type struct 去定義好之後再進行解析

  • 利用 `map[string]interface{}`轉換,但想要取資料解析後比較麻煩,不像是知道結構方便

  • 可以用map取第一層,下一層需reflect,下下層也是...或是利用斷言

  • 僅僅需要將某字串格式化可用

  • 小地方注意:在进行反序列化操作时:第二个参数应该i传地址

(ex1):https://go.dev/play/p/kFzxUGvoDNJ

json.Compact

如果json string是beautify JSON String,json.Compact可以做壓縮。

範例

轉換練習

reference

來源
筆記

json.Marshal types

e.g. func or chan refuse to serialize

struct tag 還可以有以下功能

printJson(key string, value interface{})

各个 Go 版本中,标准库 encoding/json 的性能表现 在做出使用第三方序列化库替换标准库的决定前,最好先测试下 json 序列化和反序列化是否是应用的性能瓶颈点

Go 语言中的深拷贝 copier 和 json 的性能

TBD: 編按:雖然本文章說json性能較差 但go1.17實測jaon比較好?why?

Last updated