[golang]struct 轉換為 json 字串
在 Golang 中,可以使用 encoding/json 套件將 struct 轉換為 JSON 字串。
基本做法
輸出
格式化輸出(縮進美化)
如果想要讓 JSON 字串更易讀,可以使用 json.MarshalIndent:
輸出
Struct 陣列轉 JSON
如果要轉換 多筆資料([]struct),一樣使用 json.Marshal:
輸出
總結
json.Marshal(struct):轉換為 JSON 壓縮格式json.MarshalIndent(struct, "", " "):轉換為 JSON 格式化輸出- 適用單一 Struct 或 Struct 陣列
- 標籤 (
json:"EmpID") 控制 JSON 欄位名稱
留言
張貼留言