Kirill Vorobjov Kirill Vorobjov - 5 months ago 10
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 :


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);

var operation = POST.insert;

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

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

How to convert it into json format ?


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.