Golang 读取和写入 JSON 文件:示例代码与详解
以下是一个简单的示例代码,可以读取一个包含 JSON 数据的文件,并将其解码为 Go 的数据结构,然后将该数据结构编码为 JSON 并写入到另一个文件中。
package main
import (
'encoding/json'
'fmt'
'io/ioutil'
'os'
)
type Person struct {
Name string `json:'name''
Age int `json:'age''
}
func main() {
// 读取文件中的 JSON 数据
data, err := ioutil.ReadFile('data.json')
if err != nil {
fmt.Println('读取文件失败:', err)
return
}
// 解码 JSON 数据
var people []Person
err = json.Unmarshal(data, &people)
if err != nil {
fmt.Println('解码 JSON 失败:', err)
return
}
// 修改数据
for i, p := range people {
p.Age += 1
people[i] = p
}
// 编码为 JSON
newData, err := json.Marshal(people)
if err != nil {
fmt.Println('编码 JSON 失败:', err)
return
}
// 写入到文件中
err = ioutil.WriteFile('newdata.json', newData, os.ModePerm)
if err != nil {
fmt.Println('写入文件失败:', err)
return
}
fmt.Println('处理完成!')
}
在此示例中,我们定义了一个名为Person的结构体,它具有两个字段:Name和Age。我们使用ioutil.ReadFile函数读取了一个名为data.json的文件,并使用json.Unmarshal函数将其解码为一个[]Person类型的变量people。
接着,我们简单地修改了people的数据,将它们的年龄加1。然后,我们使用json.Marshal函数将它们编码为 JSON 格式,并使用ioutil.WriteFile函数将它们写入到名为newdata.json的文件中。
这只是一个简单的示例,但是它可以帮助您了解如何使用 Go 读取和写入 JSON 数据。如果您需要更复杂的操作,请参考官方文档或其他相关资料。
原文地址: https://www.cveoy.top/t/topic/lZcW 著作权归作者所有。请勿转载和采集!