简体   繁体   中英

How to Post data from postman to Output.json file?

In the below code I am getting output like this without comma it's creating new array again I don't want like this I want like lastly I mentioned

Test.json

[
    {
        "name":"alpha",
        "password": "123"
    },
    {
        "name":"beta",
        "password": "321"
    }
]{
  "name":"Gokul",
  "pass":"098"
}

Main.js

var fs = require('fs');
var express = require('express');
var app = express();

app.post('/myData', function (req, res) {
    req.on('data', function (data) {
        console.log(data.toString());
        fs.appendFile("test.json", data, 'utf8', function (err, file) {
            if (err) { return console.log(err); }
            console.log("The file was saved!");
            res.send("Received");

        });
    });
});

var server = app.listen(8080, function () { });

But i want output like this :

[
    {
        "name":"alpha",
        "password": "123"
    },
    {
        "name":"beta",
        "password": "321"
    },
    {
        "name":"gokul",
        "password": "098"
    }
]

Can anyone help me and edit my code to the expected output?

What you want is to merge the jsons together.

What you need to do is, in that order:

  1. Read the full test.json file
  2. Parse the content as json
  3. Push the json the received into the array
  4. Write it back as a json file (stringify it before)

STOP!! Don't reinvent the wheel, what you need is similar to a local JSON database like Lowdb. Why don't you take a look at this repository . Perfect for your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM