读取本地json文件,修改数据后保存

B-E 2019-07-15 09:53:11
使用go,读取本地json文件,对文件中的数据进行修改或写入,后保存,怎么做?
...全文
723 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
B-E 2019-07-16
  • 打赏
  • 举报
回复
引用 1 楼 qybao的回复:
for example
import (
"os"
"encoding/json"
"io/ioutil"
)
type yourjson strut {
//difine your json struct
}

func main() { //ignore error handler
yourfile, _ := os.Open("yourjson.json")
defer yourfile.Close()
bs, _ := ioutil.ReadAll(yourfile) //read json file to bytes
js := &yourjson{}
json.Unmarshal(bs, js) //conver json bytes to struct
js.xxx = yyy //modify your json struct
newbs, _ := json.MarshalIndent(js, "", " ") //convert struct to bytes
ioutil.WriteFile("yournewjson.json", newbs, 0644) //write json bytes to file
}
好的,尝试了一下,成功实现。感谢大佬
qybao 2019-07-16
  • 打赏
  • 举报
回复
for example
import (
"os"
"encoding/json"
"io/ioutil"
)
type yourjson strut {
//difine your json struct
}

func main() { //ignore error handler
yourfile, _ := os.Open("yourjson.json")
defer yourfile.Close()
bs, _ := ioutil.ReadAll(yourfile) //read json file to bytes
js := &yourjson{}
json.Unmarshal(bs, js) //conver json bytes to struct
js.xxx = yyy //modify your json struct
newbs, _ := json.MarshalIndent(js, "", " ") //convert struct to bytes
ioutil.WriteFile("yournewjson.json", newbs, 0644) //write json bytes to file
}

2,187

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • Freeman Z
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧