使用node.js在JSON文件中写入/添加数据 [英] write/add data in JSON file using node.js

查看:152
本文介绍了使用node.js在JSON文件中写入/添加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用循环数据中的节点编写JSON文件
例如

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

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

loop.json中的outPut

outPut in loop.json is

id :1 square : 1

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

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

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


推荐答案

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

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


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

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

var obj = {
   table: []
};


  • 添加一些数据,如

  • Add some data to it like

    obj.table.push({id: 1, square:2});
    


  • 使用stringify将其从对象转换为字符串

  • Convert it from an object to string with stringify

    var json = JSON.stringify(obj);
    


  • 使用fs将文件写入磁盘

  • use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    


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

  • 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的数据最大有效。超过此限制,您应该使用数据库引擎。

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

    更新:

    创建一个函数,以字符串形式返回当前日期(年+月+日) 。创建名为this string + .json的文件。 fs模块有一个函数可以检查名为fs.stat(path,callback)的文件存在。
    有了这个,你可以检查文件是否存在。如果存在,请使用read函数,如果不存在,请使用create函数。使用日期字符串作为路径,因为该文件将被命名为今天日期+ .json。回调将包含一个stats对象,如果该文件不存在,该对象将为null。

    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.

    这篇关于使用node.js在JSON文件中写入/添加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆