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
     }
  }]
3
  • 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. Commented Mar 27, 2019 at 9:32
  • possible duplicate of stackoverflow.com/questions/36093042/… Commented Mar 27, 2019 at 9:56
  • Yes I see this issue and try to do the same thing but I don't want overwrite ... Commented Mar 27, 2019 at 9:58

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

8 Comments

I need to use writeFile or appendFile ?
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
@Jeremy use fs.appendFile('myjsonfile.json', json + "\n", ...)
@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.
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) {..});
|
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);
            });


        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.