Kirill Vorobjov Kirill Vorobjov - 1 year ago 48
JSON Question

Write POST received data into json file in json format

Trying to add data that was received with POST request into json file in this format :

[ {
"id": 1,
"data": "hello",
"data1": "hi",
"data2": "hey",
} ]


but right now it writes like this :

id=1&data=hello&data1=hi&data2=hey


I've read that i have to parse the data first, here is the code :

if (request.method == 'POST' && request.url == "/page") {
var body = "";
request.on('data', function (data) {
body += data;
});
request.on('end', function (req, res) {

POST = qs.parse(body);
console.log(POST);

var operation = POST.insert;

if (operation == 'insert') {
fs.readFile("file.json", "utf8", function (err, data){
var updateData = {
id: POST.id,
data: POST.data,
data1: POST.data1,
data2: POST.data2
}

var newData = qs.stringify(updateData);
fs.writeFile('file.json', newData, "utf8");
console.log(err);
})
}
});
}


How to convert it into json format ?

Answer Source

The point of qs.stringify is to take an object and turn it into a query string.

If you want JSON and not a query string, then don't use that function!

You can convert an object into JSON with JSON.stringify.