附加到 JSON 文件(Node.JS、Javascript)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29833676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append to a JSON File (Node.JS, Javascript)
提问by medemi68
I currently have a json file setup with the following format:
我目前有一个具有以下格式的 json 文件设置:
{
"OnetimeCode" : "Value"
}
And I'd like to be able to do two things:
我希望能够做两件事:
- Append to the file (change the values in the file)
- Add New Items to the File (In the same format)
- 附加到文件(更改文件中的值)
- 向文件中添加新项目(以相同的格式)
I have been searching for almost an hour trying to find either a module (for Node) or just easy sample code that would allow me to accomplish this.
我已经搜索了将近一个小时,试图找到一个模块(用于 Node)或者只是简单的示例代码,可以让我完成这个任务。
I have tried using several plugins already, but rather than appending to the file, they completely rewrite it.
我已经尝试使用几个插件,但他们没有附加到文件中,而是完全重写了它。
One of the plugins is called "jsonfile" (npm install jsonfile)
其中一个插件称为“jsonfile”(npm install jsonfile)
var jf = require('jsonfile'); // Requires Reading/Writing JSON
var jsonStr = WEAS_ConfigFile;
var obj = JSON.parse(jsonStr);
obj.push({OnetimeCode : WEAS_Server_NewOneTimeCode});
jf.writeFileSync(WEAS_ConfigFile, obj); // Writes object to file
But that does not seem to be working.
但这似乎不起作用。
Any help is appreciated! But Please, keep it simple.
任何帮助表示赞赏!但是请保持简单。
Also: I cannot use jQuery
另外:我不能使用 jQuery
回答by Plato
The code you provided with the jsonfile
library looks like a good start: you parse the json into an object, call .push()
, and save something.
您随jsonfile
库提供的代码看起来是一个好的开始:您将 json 解析为一个对象,调用.push()
并保存一些内容。
With raw Node calls (assuming the json file is a representation of an array):
使用原始节点调用(假设 json 文件是数组的表示):
var fs = require('fs');
function appendObject(obj){
var configFile = fs.readFileSync('./config.json');
var config = JSON.parse(configFile);
config.push(obj);
var configJSON = JSON.stringify(config);
fs.writeFileSync('./config.json', configJSON);
}
appendObject({OnetimeCode : WEAS_Server_NewOneTimeCode});