1

I need to append my JSON data to an array inside a JSON file. It is appending successfully. However, it does not append inside of the Brackets in the JSON file

Here is my NODE

 if (req.method == 'POST') {
    req.on('data', function (chunk) {
        fs.writeFile("comments-data.json", chunk, {'flag':'a'}, function(err) {
            if(err) {
                return console.log(err);
            }

            console.log("The file was saved!");
        })
    });
    res.end('{"msg": "success"}');
};

How can i tell it to just append inside of the brackets?

2
  • 1
    What brackets? What are you talking about? Commented Aug 11, 2016 at 21:45
  • 5
    You can't just append to a JSON file and expect it to merge into the array. You need to read the file, parse the JSON to an array, push the new element onto the array, stringify the array, and then write that to the file. Commented Aug 11, 2016 at 21:46

1 Answer 1

2

You have to parse the JSON in both the request and the file, push the requrest data onto the array, then write that back out to the file.

if (req.method == 'POST') {
    req.on('data', function(chunk) {
        var element = JSON.parse(chunk);
        fs.readFile("comments-data.json", 'r', function(err, json) {
            var array = JSON.parse(json);
            array.push(element);
            fs.writeFile("comments-data.json", JSON.stringify(array), "w", function(err) {
                if (err) {
                    console.log(err);
                    return;
                }
                console.log("The file was saved!");
            });
        });
        res.end('{"msg": "success"}');
    });
}
Sign up to request clarification or add additional context in comments.

10 Comments

You were missing a }); at the end. Also it did not recognize 'r' so i changed it to utf8. When I try to run this snippet, I receive cannot read property push of null. @Barmar
That means JSON.parse() is failing, so there's something wrong with the contents of the json file.
How should it be setup for the example of your snippet? I tried even a blank array.
The initial contents of the file should be [].
Same result with the blank array
|

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.