附加到JSON文件(Node.JS,Javascript)[重复]

时间:2021-11-29 03:53:33

This question already has an answer here:

这个问题在这里已有答案:

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.

我一直在寻找一个小时试图找到一个模块(用于节点)或只是简单的示例代码,这将允许我完成此任务。

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

1 个解决方案

#1


10  

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):

使用原始Node调用(假设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});

#1


10  

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):

使用原始Node调用(假设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});