最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - nodejs append inside json file in array format - Stack Overflow

programmeradmin0浏览0评论

I want the nodejs to append all the data in the JSON format in following format

    [{
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   }, {
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   },{
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   }]

And I want the nodejs to append more data. I m trying append but it's appending like this

{
  "name": "admin",
  "message": "dfd",
  "datetime": "2014-06-03 13:01:39"
}{
  "name": "admin",
  "message": "dfd",
  "datetime": "2014-06-03 13:01:39"
}

I m using the following code to append

    myData= { "name": "sam" , "message": "hi how are you", "datetime": "2014-5-1 4:4:4" };

    fs.appendFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
        if(err) {
          console.log(err);
        }
    });

I want the nodejs to append all the data in the JSON format in following format

    [{
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   }, {
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   },{
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   }]

And I want the nodejs to append more data. I m trying append but it's appending like this

{
  "name": "admin",
  "message": "dfd",
  "datetime": "2014-06-03 13:01:39"
}{
  "name": "admin",
  "message": "dfd",
  "datetime": "2014-06-03 13:01:39"
}

I m using the following code to append

    myData= { "name": "sam" , "message": "hi how are you", "datetime": "2014-5-1 4:4:4" };

    fs.appendFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
        if(err) {
          console.log(err);
        }
    });
Share Improve this question edited Jun 3, 2014 at 10:01 dave asked Jun 3, 2014 at 9:16 davedave 1,6795 gold badges24 silver badges32 bronze badges 3
  • what is code used for appending? – azero0 Commented Jun 3, 2014 at 9:33
  • @A-0- question is updated – dave Commented Jun 3, 2014 at 10:01
  • You might need to parse the array from the file as a javascript array, append your new data to the array and then save the array in the file. – Aliou Commented Jun 3, 2014 at 10:06
Add a ment  | 

1 Answer 1

Reset to default 9

JSON is not 'appendable' format. You have two options here:

  1. Read file, parse it, append data to array, serialize, replace file content.
  2. Switch to different file format. Actually CSV is good enough to store table-like data and is 'appendable'.
发布评论

评论列表(0)

  1. 暂无评论