013-golang中json轉換成結構體或者map
阿新 • • 發佈:2018-11-07
先拿一個json字串
jsonString := `{"name":"張三","age":20,"data":["男","未婚"]}`
func main() { jsonString := `{"name":"張三","age":20,"data":["男","未婚"]}` var stu Student err := json.Unmarshal([]byte(jsonString), &stu) if err!= nil { fmt.Println(err) return } fmt.Println(stu) } type Student struct { Name string `json:"name"` Age int `json:"age"` Data []string `json:"data"` }
用unmarshal方法哦
然後轉換成map
func main() { jsonString := `{"name":"張三","age":20,"data":["男","未婚"]}` m := make(map[string]interface{}, 4) err := json.Unmarshal([]byte(jsonString), &m) if err != nil { fmt.Println(err) return } fmt.Println(m) }