Search code examples
javascriptjsoncasperjs

How to add a json object to a json array in an external file in javascript / capserjs


I am writing to a json file in casperjs and am trying to add new objects to it.

json file looks like

 { "visited": [

{
  "id": "258b5ee8-9538-4480-8109-58afe741dc2f",
  "url": "https://................"
},
{
  "id": "5304de97-a970-48f2-9d3b-a750bad5416c",
  "url": "https://.............."
},
{
  "id": "0fc7a072-7e94-46d6-b38c-9c7aedbdaded",
  "url": "https://................."
}]}

The code to add to the array is

    var data;

    if (fs.isFile(FILENAME)) {
        data = fs.read(FILENAME);
    } else {
       data = JSON.stringify({ 'visited': [] });
    }

        var json = JSON.parse(data);

        json.visited.push(visiteddata);

     data = JSON.stringify(json, null, '\n');

     fs.write(FILENAME, data, "a");

This is starting off by adding an new { "visited" : [ ] } array with first couple of objects, below the existing { "visited" : [ ] } array and subsequently the script breaks because the json array is no longer valid json.

Can anybody point me in the right direction. Thank you in advance.


Solution

  • You have a JSON file containing some data.

    You:

    1. Read that data
    2. Modify that data
    3. Append the modified version of that data to the original file

    This means the file now has the original data and then, immediately after it, a near identical copy with a little bit added.

    You don't need the original. You only need the new version.

    You need to write to the file instead of appending to it.

    Change the 'a' flag to 'w'.