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

B-E 2019-07-15 09:53:11
使用go,读取本地json文件,对文件中的数据进行修改或写入,后保存,怎么做?
...全文
779 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
}
代码下载地址: https://pan.quark.cn/s/f302b99a3ac4 在本Electron项目之中,我们主要探索的是借助Electron框架来开发一个桌面应用程序,此应用需具备处理用户登录、信息调整以及支持窗口行为的能力,例如窗口的缩小、放大和关闭操作。不仅如此,项目还包含对本地JSON文件读取与写入功能,并且该JSON文件能够在服务器无法访问时作为数据存储的替代方案。以下将对这些功能进行详尽的说明:1. **Electron框架**: Electron是由GitHub开发的一个开源框架,其设计目的是用于构建跨操作系统的桌面应用程序。该框架整合了Node.js和Chromium浏览器引擎,使得开发者能够运用JavaScript、HTML以及CSS来开发出具有原生桌面应用特性的软件。2. **本地JSON文件读写**: 在后台服务器无法正常访问的情况下,应用程序将转向使用本地的JSON文件来进行数据交互。JSON(JavaScript Object Notation)是一种结构简单且易于人类阅读和编写的数据交换格式,同时它也便于机器进行解析和生成。Node.js中的`fs`模块提供了文件操作的接口,比如`fs.readFile()`和`fs.writeFile()`,这些接口可用于从本地文件读取保存JSON格式的数据。3. **用户登录**: 当用户尝试进行登录操作时,一般会提交用户名和密码。在服务器运行正常的情况下,这些信息会被发送到服务器端进行身份验证。然而,在本项目中,如果服务器访问出现故障,应用程序会从本地的JSON文件读取用户信息,并检查文件内是否存在对应的用户记录。若找到匹配的记录,则将用户视为成功登录。4. **修改用户信息...

2,351

社区成员

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

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