go-json
JSON是一种受到广泛支持的语言格式,JSON里一个对象是一个字符串到值的映射,用花括号和逗号分隔,JSON在go里面可以被用来编写map和结构体,譬如
type Movie struct {
Title string
Year int `json:"released"` //编码后名称变为released,不加默认用成员名
Color bool `json:"color,omitempty"`//编码后改名外加如果是空的那么不显示
Actors []string
}
var movies = []Movie{
{Title: "Casablanca", Year: 1942, Color: false,
Actors: []string{"Humphrey Bogart", "Ingrid Bergman"}},
{Title: "Cool Hand Luke", Year: 1967, Color: true,
Actors: []string{"Paul Newman"}},
{Title: "Bullitt", Year: 1968, Color: true,
Actors: []string{"Steve McQueen", "Jacqueline Bisset"}},
// ...
}
使用json.Marshal和json.MarshalIndent,前者返回一个slice,没有缩进,后者带两个参数,可以控制每一行的输出的前缀和每一段的缩进
data, err := json.MarshalIndent(movies, "", " ")
if err != nil {
log.Fatalf("JSON marshaling failed: %s", err)
}
fmt.Printf("%s\n", data)
输出
[
{
"Title": "Casablanca",
"released": 1942,
"Actors": [
"Humphrey Bogart",
"Ingrid Bergman"
]
},
{
"Title": "Cool Hand Luke",
"released": 1967,
"color": true,
"Actors": [
"Paul Newman"
]
},
{
"Title": "Bullitt",
"released": 1968,
"color": true,
"Actors": [
"Steve McQueen",
"Jacqueline Bisset"
]
}
]
解码使用unmarshaling解码成切片,可以选择性解码,即只解出需要的值
var titles []struct{ Title string }
if err := json.Unmarshal(data, &titles); err != nil {
log.Fatalf("JSON unmarshaling failed: %s", err)
}
fmt.Println(titles) // "[{Casablanca} {Cool Hand Luke} {Bullitt}]"
评论已关闭