go 语言学习笔记(16)—— JSON
json介绍
导包: encoding/json
百度百科:JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
结构体生成json
package main
import (
"encoding/json"
"fmt"
)
//成员变量名必须大写
type IT struct {
Company string
Subjects []string
Isok bool
Price float64
}
func main() {
//定义结构体并初始化
s := IT{"hhh", []string{"go", "python", "c", "c++"}, true, 6666.6}
//编码, 根据内容生成json文本
buf, err := json.Marshal(s)
//json.Marshal返回两个值, 一个是文本内容, 一个是错误
if err != nil {
fmt.Println(err)
return
} else {
//生成的字节切片, 需要转成字符型输出
fmt.Println(string(buf))
//{"Company":"hhh","Subjects":["go","python","c","c++"],"Isok":true,"Price":6666.6}
}
//格式化编码
buf, err = json.MarshalIndent(s, "", " ")
if err != nil {
fmt.Println(err)
return
} else {
//生成的字节切片, 需要转成字符型输出
fmt.Println(string(buf))
/*
{
"Company": "hhh",
"Subjects": [
"go",
"python",
"c",
"c++"
],
"Isok": true,
"Price": 6666.6
}
*/
}
}
二次编码 输出首字母小写
type IT struct {
Company string `json:"company"`
Subjects []string
Isok bool
Price float64
}
/*输出
{
"company": "hhh",
"Subjects": [
"go",
"python",
"c",
"c++"
],
"Isok": true,
"Price": 6666.6
}
*/
不输出
type IT struct {
Company string `json:"-"`
Subjects []string
Isok bool
Price float64
}
/*输出
{
"Subjects": [
"go",
"python",
"c",
"c++"
],
"Isok": true,
"Price": 6666.6
}
*/
非字符串类型输出字符串
type IT struct {
Company string
Subjects []string
Isok bool `json:",string"`
Price float64
}
/*输出
{
"Company": "hhh",
"Subjects": [
"go",
"python",
"c",
"c++"
],
"Isok": "true",
"Price": 6666.6
}
*/
map生成json
package main
import (
"encoding/json"
"fmt"
)
func main() {
m := make(map[string]interface{}, 4)
m["Company"] = "hhh"
m["Subjects"] = []string{"go", "python", "c", "c++"}
m["Isok"] = true
m["Price"] = 6666.6
buf, err := json.MarshalIndent(m, "", " ")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(buf))
}
}
/*
{
"Company": "hhh",
"Isok": true,
"Price": 6666.6,
"Subjects": [
"go",
"python",
"c",
"c++"
]
}
*/