javascript - How to seperate objects with commas when writing them to a json file using nodejs? -
i sending right click coordinates client side server side , there writing them down in json file, having coordinates of different points stored different objects. how json file looks:
{"x":344,"y":158}{"x":367,"y":152}{"x":641,"y":129}
now problem have put comma between first 2 objects in order make valid json. how can that? here request handler function:
.post(function(request, response){ console.log("request received"); var util = require('util'); var coordinates = request.body; var imagecoordinates = json.stringify(coordinates, null, 2); fs.appendfile('coords.json', imagecoordinates, finished); function finished(err){ console.log('all set.'); response.send("all ok"); } console.log('coords are:', coordinates); });
ok, 1 idea.
if alter appendfile add newline.. after each append, not make easier read if opened it, make easier parse.
eg.. fs.appendfile('coords.json', imagecoordinates + '\r\n', finished);
because can't run node here in browser, in code below pretend lines data read file after above mods newlines.
i generate valid json splitting , rejoining commas, , wrap inside array.
ps. filter(string)
filter out last array element blank due none required last comma.
let lines = '{"x":344,"y":158}\r\n{"x":367,"y":152}\r\n{"x":641,"y":129}\r\n'; var data = json.parse('[' + (lines.split('\r\n').filter(string)).join(',') + ']'); console.log(data);
Comments
Post a Comment