1

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

2
  • Unable to reproduce: echo '[]' > t.json; echo "let a = require('./t.json'); a.push({'a':'b'}); console.log(JSON.stringify(a)); > t.js then run it. node t.js, results in: [{"a":"b"}] Commented Apr 29, 2019 at 21:21
  • my output is [object Object], it's like JSON.stringify() doesn't do its job inside post handler Commented Apr 29, 2019 at 21:24

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.