🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
#### 结构体转json ``` package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func struct2json() { var person Person person.age = 11 person.Name = "张三" b, err := json.Marshal(&person) if err != nil { fmt.Println("err : ", err) return } fmt.Println(string(b)) } func main() { struct2json() } ``` #### map转json ``` func map2json() { var a map[string]interface{} a = make(map[string]interface{}) a["name"] = "李四" a["age"] = 12 a["address"] = "郑州市" b, err := json.Marshal(a) if err != nil{ fmt.Println("err, ", err) return } fmt.Println(string(b)) } 结果: {"address":"郑州市","age":12,"name":"李四"} ``` #### 切片转json ``` func slice2json() { var slice []map[string]interface{} var m1 map[string]interface{} m1 = make(map[string]interface{}) m1["name"] = "王二" m1["age"] = 13 m1["address"] = "郑州市" var m2 map[string]interface{} m2 = make(map[string]interface{}) m2["name"] = "王二" m2["age"] = 13 m2["address"] = "郑州市" slice = append(slice, m1) slice = append(slice, m2) b, err := json.Marshal(slice) if err != nil { fmt.Println("err ", err) return } fmt.Println(string(b)) } 结果: [{ "address": "郑州市", "age": 13, "name": "王二" }, { "address": "郑州市", "age": 13, "name": "王二" }] ```