mardi 5 mai 2015

making a JSON file from user's input

I'm trying to use JSON as some kind of database for my application. So the user adds an input and it's written to the JSON file, then when I need that information I can loop through the JSON. I'm using 'fs' to write the JSON format of my object inside file:

fs.appendFile('log.json',  JSON.stringify(customer) + '\n' , function(err) {
    if (err) {
        return console.log(err);
    }
    console.log('saved in log.json');
});

So my log.json looks like this:

{"name":"John","email":"john@gmail.com"}
{"name":"Peter","email":"Peter@gmail.com"}

This is still can be used if I read each line and convert it to object, but obviously it's not a valid JSON file and it'd be better if I can have this as output:

{
{"name":"John","email":"john@gmail.com"},
{"name":"Peter","email":"Peter@gmail.com"}
}

or even better:

[
{"name":"John","email":"john@gmail.com"},
{"name":"Peter","email":"Peter@gmail.com"}
]

So technically all I want to do is keeping {} and append my text inside curly braces. Please note that I can't store all of the inputs in an array/object and then write that in my log file. I want an external-module-free method to update my log.json file every time user enters new information.

Aucun commentaire:

Enregistrer un commentaire