I want the nodejs to append all the data in the JSON format in following format
[{
"name": "admin",
"message": "dfd",
"datetime": "2014-06-03 13:01:39"
}, {
"name": "admin",
"message": "dfd",
"datetime": "2014-06-03 13:01:39"
},{
"name": "admin",
"message": "dfd",
"datetime": "2014-06-03 13:01:39"
}]
And I want the nodejs to append more data. I m trying append but it's appending like this
{
"name": "admin",
"message": "dfd",
"datetime": "2014-06-03 13:01:39"
}{
"name": "admin",
"message": "dfd",
"datetime": "2014-06-03 13:01:39"
}
I m using the following code to append
myData= { "name": "sam" , "message": "hi how are you", "datetime": "2014-5-1 4:4:4" };
fs.appendFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
}
});
To append json data/elements to a json file, read the file, parse the JSON, push the new result to the array, convert into a string, and save it.
Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.
To update a JSON object in a file, import the json library, read the file with json. load(file ), add the new entry to the list or dictionary data structure data , and write the updated JSON object with json. dump(data, file) .
In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
JSON is not 'appendable' format. You have two options here:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With