我试图写JSON文件使用节点从循环数据,例如:

let jsonFile = require('jsonfile');

for (i = 0; i < 11; i++) {
    jsonFile.writeFile('loop.json', "id :" + i + " square :" + i * i);
}

循环输出。json是:

id :1 square : 1

但是我想要这样的输出文件(如下所示),而且如果我再次运行该代码,它应该在相同的现有JSON文件中添加新的输出元素:

{
   "table":[
      {
         "Id ":1,
         "square ":1
      },
      {
         "Id ":2,
         "square ":3
      },
      {
         "Id ":3,
         "square ":9
      },
      {
         "Id ":4,
         "square ":16
      },
      {
         "Id ":5,
         "square ":25
      },
      {
         "Id ":6,
         "square ":36
      },
      {
         "Id ":7,
         "square ":49
      },
      {
         "Id ":8,
         "square ":64
      },
      {
         "Id ":9,
         "square ":81
      },
      {
         "Id ":10,
         "square ":100
      }
   ]
}

我想使用相同的文件,我第一次创建,但每当我运行该代码的新元素应该添加在同一文件

const fs = require('fs');

let obj = {
    table: []
};

fs.exists('myjsonfile.json', function(exists) {

    if (exists) {

        console.log("yes file exists");

        fs.readFile('myjsonfile.json', function readFileCallback(err, data) {

            if (err) {
                console.log(err);
            } else {
                obj = JSON.parse(data);

                for (i = 0; i < 5; i++) {
                    obj.table.push({
                        id: i,
                        square: i * i
                    });
                }

                let json = JSON.stringify(obj);
                fs.writeFile('myjsonfile.json', json);
            }
        });
    } else {

        console.log("file not exists");

        for (i = 0; i < 5; i++) {
            obj.table.push({
                id: i,
                square: i * i
            });
        }

        let json = JSON.stringify(obj);
        fs.writeFile('myjsonfile.json', json);
    }
});

当前回答

如果这个JSON文件不会随着时间的推移变得太大,你应该尝试:

Create a JavaScript object with the table array in it var obj = { table: [] }; Add some data to it, for example: obj.table.push({id: 1, square:2}); Convert it from an object to a string with JSON.stringify var json = JSON.stringify(obj); Use fs to write the file to disk var fs = require('fs'); fs.writeFile('myjsonfile.json', json, 'utf8', callback); If you want to append it, read the JSON file and convert it back to an object fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){ if (err){ console.log(err); } else { obj = JSON.parse(data); //now it an object obj.table.push({id: 2, square:3}); //add some data json = JSON.stringify(obj); //convert it back to json fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back }});

这将有效地工作于高达100 MB的数据。超过这个限制,您应该使用数据库引擎。

更新:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

其他回答

如果这个JSON文件不会随着时间的推移变得太大,你应该尝试:

Create a JavaScript object with the table array in it var obj = { table: [] }; Add some data to it, for example: obj.table.push({id: 1, square:2}); Convert it from an object to a string with JSON.stringify var json = JSON.stringify(obj); Use fs to write the file to disk var fs = require('fs'); fs.writeFile('myjsonfile.json', json, 'utf8', callback); If you want to append it, read the JSON file and convert it back to an object fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){ if (err){ console.log(err); } else { obj = JSON.parse(data); //now it an object obj.table.push({id: 2, square:3}); //add some data json = JSON.stringify(obj); //convert it back to json fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back }});

这将有效地工作于高达100 MB的数据。超过这个限制,您应该使用数据库引擎。

更新:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

对于格式化jsonfile提供了空格选项,您可以将其作为参数传递:

   jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
         console.error(err);
   })

或者使用jsonfile。空格= 4。点击这里阅读详情。

我不建议每次都在循环中写入文件,而是在循环中构造JSON对象并在循环外写入文件。

var jsonfile = require('jsonfile');
var obj={
     'table':[]
    };

for (i=0; i <11 ; i++){
       obj.table.push({"id":i,"square":i*i});
}
jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
      console.log(err);
});

请试试下面的程序。您可能希望得到这样的输出。

var fs = require('fs');

var data = {}
data.table = []
for (i=0; i <26 ; i++){
   var obj = {
       id: i,
       square: i * i
   }
   data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
    if (err) throw err;
    console.log('complete');
    }
);

将这个程序保存在一个javascript文件中,比如square.js。

然后使用命令节点square.js从命令提示符运行程序

它所做的是,每次执行命令时,简单地用一组新数据覆盖现有文件。

快乐的编码。

我同意以上的答案,这是一个完整的阅读和写作的样本,任何人都需要它。

     router.post('/', function(req, res, next) {

        console.log(req.body);
        var id = Math.floor((Math.random()*100)+1);

        var tital = req.body.title;
        var description = req.body.description;
        var mynotes = {"Id": id, "Title":tital, "Description": description};
        
        fs.readFile('db.json','utf8', function(err,data){
            var obj = JSON.parse(data);
            obj.push(mynotes);
            var strNotes = JSON.stringify(obj);
            fs.writeFile('db.json',strNotes, function(err){
                if(err) return console.log(err);
                console.log('Note added');
            });

        })
        
        
    });


  

try

var fs = require("fs");
var sampleObject = { your data };

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {  console.error(err);  return; };
    console.log("File has been created");
});