JSON 数据
Posted chaoyang.xu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSON 数据相关的知识,希望对你有一定的参考价值。
结构体数据转json
1 package main 2 3 import ( 4 "fmt" 5 "encoding/json" 6 7 ) 8 9 10 //结构体 11 type Person struct { 12 Name string 13 Age int 14 Rmb float64 15 Sex bool 16 Hobby []string 17 } 18 19 20 21 22 func main() { 23 Person :=Person{"小小",50,123.45,true,[]string{"吃","喝","玩"}} 24 25 bytes,err := json.Marshal(Person) 26 if err !=nil{ 27 fmt.Println("序列化失败,err=",err) 28 return 29 } 30 fmt.Println(string(bytes)) //强制类型转换bytes转为string 31 } 32 33 /* 34 {"Name":"小小","Age":50,"Rmb":123.45,"Sex":true,"Hobby":["吃","喝","玩"]} 35 */
map转json
1 package main 2 3 import ( 4 "fmt" 5 "encoding/json" 6 7 ) 8 9 func main() { 10 dataMap :=make(map[string]interface{}) //stings做键,空接口做数值,任意类型。 11 dataMap["Name"]="小" 12 dataMap["Age"]=50 13 dataMap["Rmb"]=123.45 14 dataMap["Sex"]=true 15 dataMap["Hobby"]=[]string{"吃","喝","玩"} 16 17 18 bytes,err := json.Marshal(dataMap) 19 if err !=nil{ 20 fmt.Println("序列化失败,err=",err) 21 return 22 } 23 fmt.Println(string(bytes)) //强制类型转换bytes转为string 24 25 } 26 /* 27 {"Age":50,"Hobby":["吃","喝","玩"],"Name":"小","Rmb":123.45,"Sex":true} 28 */
切片转JSON
1 package main 2 3 import ( 4 "fmt" 5 "encoding/json" 6 7 ) 8 9 func main() { 10 11 dataMap1 :=make(map[string]interface{}) //stings做键,空接口做数值,任意类型。 12 dataMap1["Name"]="小" 13 dataMap1["Age"]=50 14 15 16 dataMap2 :=make(map[string]interface{}) //stings做键,空接口做数值,任意类型。 17 dataMap2["Name"]="大" 18 dataMap2["Age"]=60 19 20 //将数据添加到切片中 21 dataSlice := make([]map[string]interface{},0) 22 dataSlice = append(dataSlice,dataMap1,dataMap2) 23 24 25 bytes,err := json.Marshal(dataSlice) 26 if err !=nil{ 27 fmt.Println("序列化失败,err=",err) 28 return 29 } 30 fmt.Println(string(bytes)) //强制类型转换bytes转为string 31 32 } 33 34 /* 35 [{"Age":50,"Name":"小"},{"Age":60,"Name":"大"}] 36 */
以上是关于JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章