golang學習筆記 --- struct 巢狀
阿新 • • 發佈:2020-07-28
定義結構體
type Btn struct{ Name string `json:"name"` Type string `json:"type"` Url string `json:"url"` Sub_button []Btn `json:"sub_button,omitempty"` //值為空時 直接忽略 UnShow string `json"-"` //忽略欄位 } type menu struct{ Button []Btn `json:"button"` }
結構體命名需要大寫 才會匯出到json串中, 可以通過 struct tag 設定匯出的別名, 可以通過 omitempty 忽略值為空的欄位
示例:
package main import ( "encoding/json" "fmt" ) type Btn struct { Name string `json:"name"` Type string `json:"type"` Url string `json:"url"` Sub_button []Btn `json:"sub_button,omitempty"` //值為空時 直接忽略 UnShow string `json"-"` //忽略欄位 } type Menu struct { Button []Btn `json:"button"` } func main() { jsonData := Menu{ Button: []Btn{ {Name: "home", Type: "view", Url: "https://www.qq.com/auth"}, {Name: "tool", Sub_button: []Btn{ {Name: "a1", Type: "view", Url: "https://www.qq.com/a1"}, {Name: "a2", Type: "view", Url: "https://www.qq.com/a2"}, {Name: "a3", Type: "view", Url: "https://www.qq.com/a3"}, }}, {Name: "other", Sub_button: []Btn{ {Name: "a1", Type: "view", Url: "https://www.qq.com/a1"}, {Name: "a2", Type: "view", Url: "https://www.qq.com/a2"}, {Name: "a3", Type: "view", Url: "https://www.qq.com/a3"}, }}, }, } str, err := json.Marshal(jsonData) if err != nil { panic(err) } fmt.Println(string(str)) }