2

I'm append JSON into a file.I'm using appendFile for append into the file. I'm using a specific JSON structure

And my problem is: how can I change the character '][' by ','

I think I need to use readFile and the function replace ?

Need help, thanks in advance

  var table = []


  table.push({"executionDate":date,
     "issueID":key,
     "priority":{
     "jira": priority, 
     "computed":score1
     },
     "expectedValue":{
           "jira": expected, 
           "computed":score2
     }
  })

  var json = JSON.stringify(table);


  fs.appendFile('myjsonfile.json', json, 'utf8', function (err) {
     if (err) console.error(err)
     });

Actual result:

  [{
     "executionDate": 25 / 03 / 2019,
     "issueID": 1,
     "priority": {
        "jira": important,
        "computed": 10
     },
     "expectedValue": {
        "jira": expected,
        "computed": 20
     }
  }
  ]
  [{
     "executionDate": 26 / 03 / 2019,
     "issueID": 2,
     "priority": {
        "jira": important,
        "computed": 20
     },
     "expectedValue": {
        "jira": expected,
        "computed": 30
     }
  }]

Expected result:

  [{
     "executionDate": 25 / 03 / 2019,
     "issueID": 1,
     "priority": {
        "jira": important,
        "computed": 10
     },
     "expectedValue": {
        "jira": expected,
        "computed": 20
     }
  }
  ,
  {
     "executionDate": 26 / 03 / 2019,
     "issueID": 2,
     "priority": {
        "jira": important,
        "computed": 20
     },
     "expectedValue": {
        "jira": expected,
        "computed": 30
     }
  }]
jeremy
  • 165
  • 10
  • 1
    you don't want to append the file but push the data in json array from file, for that you will have to read the json then extend the data and write it back to the file. – AZ_ Mar 27 '19 at 09:32
  • possible duplicate of https://stackoverflow.com/questions/36093042/how-do-i-add-to-an-existing-json-file-in-node-js – AZ_ Mar 27 '19 at 09:56
  • Yes I see this issue and try to do the same thing but I don't want overwrite ... – jeremy Mar 27 '19 at 09:58

2 Answers2

0

With append you cannot do that. Read the first comment in order to see how to achieve your goal.

Here I propose another way of doing it that does not comply with your expected result. But in the comments I cannot enter code blocks, that is why I place it here.

I suggest appending each time your JSON and a newline "\n". Then, when you read the file, split by newline and parse each line separately:

var data = contents.trim()
                   .split(/\n/g)
                   .map(line => JSON.parse(line)[0]);

That is, if you always have exactly one item in your array.

If you have more than one item per appended entry:

var data = [];
contents.trim()
        .split(/\n/g)
        .map(JSON.parse)
        .forEach(entry => data.push(...entry));
jotaelesalinas
  • 1,387
  • 1
  • 11
  • 24
  • I need to use writeFile or appendFile ? – jeremy Mar 27 '19 at 09:36
  • you don't need a /g with the split, and the file will not be a json anymore, each line also will never be a JSON from the contents of existing data in json file so JSON.parse(line) will throw exception – AZ_ Mar 27 '19 at 09:36
  • @Jeremy use `fs.appendFile('myjsonfile.json', json + "\n", ...)` – jotaelesalinas Mar 27 '19 at 09:40
  • @AZ_ you are right, my answer does not solve the problem as requested in the expected result (I gave your comment a +1!) But it works. I use it all the time. This is a recurring issue with JSON and I don't like reading and writing the whole file each time I want to append something. – jotaelesalinas Mar 27 '19 at 09:43
  • I'm doing this: data = json.trim().split(/\n/g).map(line => JSON.parse(line)[0]); fs.appendFile('myjsonfile.json', JSON.stringify(data)+"\n", 'utf8', function (err) {..}); – jeremy Mar 27 '19 at 09:46
  • @jeremy the code I proposed is used _when reading_ the data back from the file. I am assuming that your application produces and consumes the contents of the file, so you have total control over how you write and read the data. If you cannot control how the data is read and you absolutely need the file to contain just a valid JSON array, use the solution proposed by AZ_ (reading everything, pushing your new items and writing back). – jotaelesalinas Mar 27 '19 at 09:50
  • Yes I need the file to contain a valid JSON ... But when I'm using the solution proposes by AZ_, it's overwritting all element ... – jeremy Mar 27 '19 at 09:52
  • @jotaelesalinas if you are doing that quite a while then that's not very correct, if you plan to append the file later better create text files rather JSON files because it will never be a JSON anymore. – AZ_ Mar 27 '19 at 09:55
0

Finally I find :

        var table = []

        table.push({"executionDate":date,
        "issueID":key,
        "priority":{
            "jira": priority, 
            "computed":score1
        },
        "expectedValue":{
            "jira": expected, 
            "computed":score2
        }
        })

        var json = JSON.stringify(table);


        fs.appendFile('myjsonfile.json', json, 'utf8', function (err) {
            if (err) console.error(err)
        });

        fs.readFile('myjsonfile.json', 'utf8', function (err,data) {
            if (err) {
                return console.log(err);
            }
            var result = data.replace('][',',');

            fs.writeFile('myjsonfile.json', result, 'utf8', function (err) {
                if (err) return console.log(err);
            });


        });
jeremy
  • 165
  • 10