JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的数据交换格式,因简单、可读性强被广泛使用。
JSON编码即将Go数据类型转换为JSON字符串
map转json
package main
import (
"encoding/json"
"fmt"
)
func main() {
m:= map[string][]string{
"name":{"flower"},
"type":{"玫瑰","百合"},
}
// map 转json
if data,err:= json.Marshal(m);err==nil{
fmt.Printf("%s",data)
}
fmt.Println("")
if data,err:= json.MarshalIndent(m,""," ");err==nil{
fmt.Printf("%s",data)
}
}
输出:
{"name":["flower"],"type":["玫瑰","百合"]}
{
"name": [
"flower"
],
"type": [
"玫瑰",
"百合"
]
}
Deb
package main
import (
"encoding/json"
"fmt"
)
// 通过结构体标签,改变json的key
type User struct {
name string `json:"_name"`
age int `json:"_age"`
sex uint `json:"-"`
address string
}
func main() {
user:=User{
name: "yo",
age:20,
sex:1,
address: "polaris",
}
if data,err:= json.MarshalIndent(user,""," ");err==nil{
fmt.Printf("%s",data)
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章