CodeRonin
CodeRonin

Reputation: 2109

JSON stringify returns [object Object]

I have read some other questions like this, but nobody has the right solution to my problem.

I have an empty a json file named apartments.json:

[]

I want to store a list of apartments in it. I retrieve an apartment from a post request and I'm using node express (v8.10). This is the code:

router.post('/', (req, res, next) => {

   let apa = {
       id: req.body.id,
       address: req.body.address
  }

  let apartments = require('path/to/json');
  apartments.push(apa);
  let str = JSON.stringify(apartments);
  console.log(str);
)};

I want to store back the new content to apartments.json after updated, the problem is that stringify() returns [object Object]. I have tried to stringify apartments and apa to test it, but it gives me always the same thing

Upvotes: 1

Views: 198

Answers (1)

CodeRonin
CodeRonin

Reputation: 2109

For everyone that will face my same problem, this is how I solved this issue:

router.post('/', (req, res, next) => {

  let apa = {
      id: req.body.id,
      address: req.body.address
 }

 let apas = [];
 let apartments = require('path/to/json');
 apas.push(apa);
 let str = "[ ";
 for(let i = 0; i < apas.length - 1; i++) {
    strAlt += '{"id": ' + apas[i].id + ', "name": "' + apas[i].name + '"}, ';
}
strAlt += '{"id": ' + apas[apas.length - 1].id + ', "name": "' + apas[apas.length - 1].name + '"} ] ';
console.log("stringify manuale: " + strAlt);
fs.writeFile(__dirname + "/../db/apartments.json", strAlt, (err) => {
    if(err) throw err;
    console.log("file saved!");
});
console.log(apartments);
res.status(200).send(apa);

Upvotes: 1

Related Questions