使用json.Marshal与os.WriteFile可快速写入小数据,json.Encoder适合大对象流式写入,结合MarshalIndent可格式化输出,map或slice同理处理。

在Golang中写入JSON文件是一个常见的操作,尤其是在处理配置、数据导出或API响应缓存时。Go语言通过encoding/json包提供了强大的JSON支持,结合os和io包可以轻松实现将数据写入JSON文件。以下是几种常用的写入方法汇总。
使用 json.Marshal 和 ioutil.WriteFile 写入
这是最简单直接的方式:先将Go结构体或map序列化为JSON字节流,再写入文件。
注意:Go 1.16后推荐使用os.WriteFile替代ioutil.WriteFile。
package main
import (
"encoding/json"
"os"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
func main() {
person := Person{
Name: "Alice",
Age: 30,
Email: "alice@example.com",
}
// 序列化为JSON
data, err := json.Marshal(person)
if err != nil {
panic(err)
}
// 写入文件,带格式缩进可使用 MarshalIndent
err = os.WriteFile("person.json", data, 0644)
if err != nil {
panic(err)
}
}
使用 json.Encoder 写入(适合大对象或流式写入)
当你需要将大量数据或多个JSON对象写入同一个文件时,json.Encoder更高效,它可以直接写入io.Writer,无需先生成完整字节切片。
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"encoding/json"
"os"
)
func main() {
file, err := os.Create("data.json")
if err != nil {
panic(err)
}
defer file.Close()
encoder := json.NewEncoder(file)
// 可选:美化输出
encoder.SetIndent("", " ")
data := map[string]interface{}{
"name": "Bob",
"age": 25,
}
err = encoder.Encode(data)
if err != nil {
panic(err)
}
}
写入格式化(带缩进)的JSON
如果你希望生成的JSON文件可读性更强,使用json.MarshalIndent代替json.Marshal。
data, err := json.MarshalIndent(person, "", " ")
if err != nil {
panic(err)
}
err = os.WriteFile("pretty.json", data, 0644)
if err != nil {
panic(err)
}
第二个参数是前缀(通常为空),第三个是每个层级的缩进字符,如两个空格或\t。
处理 map 或 slice 的写入
无论是map[string]interface{}还是切片[]Person,写入方式一致。
people := []Person{
{Name: "Alice", Age: 30},
{Name: "Bob", Age: 25},
}
data, _ := json.MarshalIndent(people, "", " ")
os.WriteFile("people.json", data, 0644)
基本上就这些常用方法。选择哪种方式取决于你的场景:小数据用Marshal + WriteFile最方便;大数据或需流式处理时用json.Encoder更节省内存。同时记得处理错误,确保文件正确写入。










