使用node.js在JSON文件中编写/添加数据

时间:2021-12-19 06:42:26

I am trying to write JSON file using node from loop data eg

我正在尝试使用循环数据中的node编写JSON文件

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

outPut in loop.json is

输出循环。json是

id :1 square : 1

but I want output file like this (below) and also if I run that code again it should add that new output as elements in same existing JSON file

但是我想要这样的输出文件(如下所示),而且如果我再次运行该代码,它应该将新的输出作为相同的已有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
    }
  ]
}

I want to use same file that I created 1st time but whenever I run that code new elements should add in that same file

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

var fs = require('fs');

var 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});
        }
        var 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});
        }
        var json = JSON.stringify(obj);
        fs.writeFile('myjsonfile.json', json);
        }
    });

5 个解决方案

#1


151  

If this json file won't become too big over the time you should try:

如果这个json文件在你应该尝试的时候不会变得太大:

  1. Create a javascript object with the table array in it

    创建一个包含表数组的javascript对象

    var obj = {
       table: []
    };
    
  2. Add some data to it like

    向它添加一些数据

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to string with stringify

    用stringify将它从一个对象转换为字符串

    var json = JSON.stringify(obj);
    
  4. use fs to write the file to disk

    使用fs将文件写到磁盘

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. if you want to append it read the json file and convert it back to an object

    如果想要附加它,请读取json文件并将其转换回对象

    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 
    }});
    

This will work for data big as 100 MB max effectively. Over this limit, you should use a database engine.

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

UPDATE:

更新:

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的文件。fs模块有一个函数,可以检查名为fs的文件是否存在。回调,stat(路径)。有了这个,您可以检查文件是否存在。如果存在,使用read函数(如果不存在),使用create函数。使用日期字符串作为路径,因为文件将被命名为today date + .json。回调将包含一个stats对象,如果该文件不存在,该对象将为空。

#2


6  

Please try the following program. You might be expecting this output.

请尝试下面的程序。您可能期望得到这个输出。

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');
    }
);

Save this program in a javascript file, say, square.js.

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

Then run the program from command prompt using the command node square.js

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

What it does is, simply overwriting the existing file with new set of data, every time you execute the command.

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

Happy Coding.

快乐的编码。

#3


5  

you should read the file, every time you want to add a new property to the json, and then add the the new properties

每次要向json添加新属性时,都应该读取文件,然后添加新属性

var fs = require('fs');
fs.readFile('data.json',function(err,content){
  if(err) throw err;
  var parseJson = JSON.parse(content);
  for (i=0; i <11 ; i++){
   parseJson.table.push({id:i, square:i*i})
  }
  fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
    if(err) throw err;
  })
})

#4


3  

For formatting jsonfile gives spaces option which you can pass as a parameter:

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

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

Or use jsonfile.spaces = 4. Read details here.

或使用jsonfile。空间= 4。阅读细节。

I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.

我不建议每次在循环中写入文件,而是在循环中构造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);
});

#5


0  

You can also import and use this open source write-json-file component.

您还可以导入和使用这个开源的write-json-file组件。

Example:

例子:

const writeJsonFile = require('bit/global/write-json-file');
const jsonFile = "/tmp/exampleFile.json";
writeJsonFile(jsonFile,{isThisReal:ture,author:amit}).catch(err => console.log(err));

#1


151  

If this json file won't become too big over the time you should try:

如果这个json文件在你应该尝试的时候不会变得太大:

  1. Create a javascript object with the table array in it

    创建一个包含表数组的javascript对象

    var obj = {
       table: []
    };
    
  2. Add some data to it like

    向它添加一些数据

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to string with stringify

    用stringify将它从一个对象转换为字符串

    var json = JSON.stringify(obj);
    
  4. use fs to write the file to disk

    使用fs将文件写到磁盘

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. if you want to append it read the json file and convert it back to an object

    如果想要附加它,请读取json文件并将其转换回对象

    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 
    }});
    

This will work for data big as 100 MB max effectively. Over this limit, you should use a database engine.

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

UPDATE:

更新:

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的文件。fs模块有一个函数,可以检查名为fs的文件是否存在。回调,stat(路径)。有了这个,您可以检查文件是否存在。如果存在,使用read函数(如果不存在),使用create函数。使用日期字符串作为路径,因为文件将被命名为today date + .json。回调将包含一个stats对象,如果该文件不存在,该对象将为空。

#2


6  

Please try the following program. You might be expecting this output.

请尝试下面的程序。您可能期望得到这个输出。

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');
    }
);

Save this program in a javascript file, say, square.js.

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

Then run the program from command prompt using the command node square.js

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

What it does is, simply overwriting the existing file with new set of data, every time you execute the command.

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

Happy Coding.

快乐的编码。

#3


5  

you should read the file, every time you want to add a new property to the json, and then add the the new properties

每次要向json添加新属性时,都应该读取文件,然后添加新属性

var fs = require('fs');
fs.readFile('data.json',function(err,content){
  if(err) throw err;
  var parseJson = JSON.parse(content);
  for (i=0; i <11 ; i++){
   parseJson.table.push({id:i, square:i*i})
  }
  fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
    if(err) throw err;
  })
})

#4


3  

For formatting jsonfile gives spaces option which you can pass as a parameter:

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

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

Or use jsonfile.spaces = 4. Read details here.

或使用jsonfile。空间= 4。阅读细节。

I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.

我不建议每次在循环中写入文件,而是在循环中构造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);
});

#5


0  

You can also import and use this open source write-json-file component.

您还可以导入和使用这个开源的write-json-file组件。

Example:

例子:

const writeJsonFile = require('bit/global/write-json-file');
const jsonFile = "/tmp/exampleFile.json";
writeJsonFile(jsonFile,{isThisReal:ture,author:amit}).catch(err => console.log(err));