Here's my code for my post request if it matters
router.post('/', (req, res) => {
const newStudent = {
// will deal with making random ID's later
id: 4,
studentID: req.body.studentID,
firstName: req.body.firstName,
lastName: req.body.lastName
}
database.push(newStudent);
fs.writeFile('db/db.json', JSON.stringify(database), function() {})
res.json(database);
})
The POST request works properly and it rewrites my db.json file to include my new object. Problem is, my array of objects is now all on one line. This is how my db.json file looks before the post request:
[
{
"id": 1,
"studentID": 4758456,
"firstName": "sample1",
"lastName": "student1"
},
{
"id": 2,
"studentID": 5374867,
"firstName": "sample2",
"lastName": "student2"
},
{
"id": 3,
"studentID": 2324234,
"firstName": "sample3",
"lastName": "student3"
}
]
Afterwards, it just shows all on one line like so:
[{"id":1,"studentID":4758456,"firstName":"sample1","lastName":"student1"},{"id":2,"studentID":5374867,"firstName":"sample2","lastName":"student2"},{"id":3,"studentID":2324234,"firstName":"sample3","lastName":"student3"},{"id":4,"studentID":"3465475","firstName":"sample4","lastName":"student4"}]
I know it doesn't matter too much, but is it supposed to be like this, or is there an easy way to get it to format correctly again?
CodePudding user response:
Refer here : How can I pretty-print JSON using node.js?
JSON.stringify's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces). Node can write to your filesystem with fs. Example: