JSON格式转换
读取json格式文件:
b, err := ioutil.ReadFile("./PermissionData/systemPermissionData.json") if err != nil { ctx.Error(errors.New("file not found")) } var resp interface{} jsoniter.Unmarshal(b, &resp)
1、map映射类型--->> JSON :
var toJson map[string]string toJson = map[string]string{ "k1":"v1", "k2":"v2", } data, err := json.MarshalIndent(toJson, "", " ") if err != nil { log.Fatalf("JSON marshaling failed: %s", err) } fmt.Printf("%s\n", data)
结果:
{ "k1": "v1", "k2": "v2" }
2、struct结构体类型 --->> JSON :
var toJson struct{ Name string Age int } toJson.Name = "kitty" toJson.Age = 3 data, err := json.MarshalIndent(toJson, "", " ") if err != nil { log.Fatalf("JSON marshaling failed: %s", err) } fmt.Printf("%s\n", data)
结果:
{ "Name": "kitty", "Age": 3 }
3、[]slice切片类型 ---->> JSON :
var toJson = []string{"str1", "str2","...",} data, err := json.MarshalIndent(toJson, "", " ") if err != nil { log.Fatalf("JSON marshaling failed: %s", err) } fmt.Printf("%s\n", data)
结果:
[ "str1", "str2", "..." ]
==========
3、[]slice里面嵌套map类型
var toJson = []map[string]string{ {"k1":"v1", "k2":"v2"}, {"k3":"v3", "k4":"v4"}, } data, err := json.MarshalIndent(toJson, "", " ") if err != nil { log.Fatalf("JSON marshaling failed: %s", err) } fmt.Printf("%s\n", data)
结果:
[ { "k1": "v1", "k2": "v2" }, { "k3": "v3", "k4": "v4" } ]
4、[]slice里面嵌套struct结构体:
type User struct { Name string Age int } var user1 = &User{ Name:"kitty", Age:11, } var user2 = &User{ Name:"kitty", Age:11, } var toJson = []*User{ user1, user2, } data, err := json.MarshalIndent(toJson, "", " ") if err != nil { log.Fatalf("JSON marshaling failed: %s", err) } fmt.Printf("%s\n", data)
结果:
[ { "Name": "kitty", "Age": 11 }, { "Name": "kitty", "Age": 11 } ]
5、多级嵌套:
type Address struct { Address string } type User struct { Name string Age int Addr *Address } var user1 = &User{ Name:"kitty", Age:11, Addr:&Address{ Address:"beijing", }, } var user2 = &User{ Name:"Masha", Age:18, Addr:&Address{ Address:"shanghai", }, } var toJson = []*User{ user1, user2, } data, err := json.MarshalIndent(toJson, "", " ") if err != nil { log.Fatalf("JSON marshaling failed: %s", err) } fmt.Printf("%s\n", data)
结果:
[ { "Name": "kitty", "Age": 11, "Addr": { "Address": "beijing" } }, { "Name": "Masha", "Age": 18, "Addr": { "Address": "shanghai" } } ]