在数据交换与存储中,JSON、CSV、XML 是常见格式。Go 标准库为这些格式提供了强大且易用的支持,涵盖结构体映射、读写文件、编码解码等操作。
一、JSON处理(encoding/json
)
1. 基本使用:结构体 <-> JSON
css
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email,omitempty"` // 可选字段
}
user := User{Name: "Alice", Age: 30}
data, _ := json.Marshal(user)
fmt.Println(string(data)) // {"name":"Alice","age":30}
2. 反序列化 JSON -> 结构体
css
jsonStr := `{"name":"Bob","age":25}`
var u User
err := json.Unmarshal([]byte(jsonStr), &u)
fmt.Printf("%+v\n", u)
3. 处理嵌套结构、数组、map
go
type Post struct {
ID int
Author User
Tags []string
}
post := Post{ID: 1, Author: user, Tags: []string{"go", "json"}}
jsonBytes, _ := json.MarshalIndent(post, "", " ")
fmt.Println(string(jsonBytes))
二、CSV处理(encoding/csv
)
CSV 通常用于表格数据、Excel 导出等,Go 提供简单读写接口。
1. 写入 CSV 文件
go
file, _ := os.Create("data.csv")
defer file.Close()
writer := csv.NewWriter(file)
writer.Write([]string{"Name", "Age", "Email"})
writer.Write([]string{"Tom", "22", "[email protected]"})
writer.Flush()
2. 读取 CSV 文件
go
file, _ := os.Open("data.csv")
defer file.Close()
reader := csv.NewReader(file)
records, _ := reader.ReadAll()
for _, record := range records {
fmt.Println(record)
}
3. 自定义分隔符(如 ;
)
ini
reader := csv.NewReader(file)
reader.Comma = ';'
CSV 不支持结构体直接映射,需手动转换。
三、XML处理(encoding/xml
)
1. 基本结构体标签
go
type Note struct {
To string `xml:"to"`
From string `xml:"from"`
Message string `xml:"message"`
}
2. 序列化:结构体 -> XML
go
note := Note{"Tom", "Jerry", "Hello, XML!"}
data, _ := xml.MarshalIndent(note, "", " ")
fmt.Println(xml.Header + string(data))
输出:
xml
<?xml version="1.0" encoding="UTF-8"?>
<Note>
<to>Tom</to>
<from>Jerry</from>
<message>Hello, XML!</message>
</Note>
3. 反序列化:XML -> 结构体
swift
input := `<Note><to>Tom</to><from>Jerry</from><message>Hi</message></Note>`
var n Note
xml.Unmarshal([]byte(input), &n)
fmt.Printf("%+v\n", n)
4. 属性与嵌套结构
go
type Book struct {
Title string `xml:"title,attr"`
Author string `xml:"author"`
}
type Library struct {
XMLName xml.Name `xml:"library"`
Books []Book `xml:"book"`
}
四、三者对比与适用场景
格式 | 特点 | 场景 |
---|---|---|
JSON | 结构清晰、易于网络传输 | Web API、前后端通信 |
CSV | 体积小、表格友好 | 报表导入导出、数据分析 |
XML | 可扩展、支持属性与命名空间 | 配置文件、SOAP、嵌套数据 |
五、实战建议
- • 使用
json.MarshalIndent
便于调试输出。 - • 自定义字段名与
omitempty
控制输出字段。 - •
csv
通常用于轻量级数据交换,不建议嵌套。 - • 解析 XML 时注意标签与命名空间。