0

In the function below my aim is write a JSON file with array of data (in string). But push() function that is under comments stop executing code. Without this line of code everything works. However, I need to use this function. What should I do or maybe I should use something different at all?

router.put('/insert_Data', function (req, res, next) {
  let body = req.body;
  let data = [];
  data.push(body['d']);
  let jsonData = [];

  for (let i = 0; i < data.length; i++) {
    let from = Number(data[i].from);
    let to = Number(data[i].to);
    let type = Number(data[i].type);
    let time = Number(data[i].time);
    let price = Number(data[i].price);
    let line = data[i].line;
    let coin = data[i].coin;
    from = from ? from : 0; 
    to = to ? to : 0;
    type = type ? type : 0;
    time = time ? time : 0;
    price = price ? price : 0;
    let item = `${from},${to},${type},${time},${price},${line},${coin}`;
    console.log('item', item);
    console.log('jsonData', jsonData);
    //jsonData[i].push(item); // TODO: здесь не выполняется!
    console.log('jsonData', jsonData);
  }
  console.log('after', jsonData);
  jsonData = JSON.stringify(jsonData, null, 1);
  // create new JSON
  fs.writeFileSync('output.json', jsonData, function(err){
    console.log(err.message);
  });

  
  
  
  res.end();
});

I use Postman to check this code. req.body is the following JSON:

{
    "d": {
        "from": 4444,
        "to": 222,
        "type": 322,
        "time": 222222,
        "price": "334",
        "line": "333",
        "coin": 333
    }
}

router variable is simple, it is only express.js running on port 5000.

2
  • Soloveychuk Which DB u use? Create model and then it is easy with async/await to PUT,or perform any other API method. Commented Feb 26, 2021 at 14:58
  • I do not use any DB. Just writing to new json file. Commented Feb 27, 2021 at 9:35

1 Answer 1

2

You can only push on arrays. What you are doing is trying to push in an element of an array, but the array is empty. I guess what you're trying to do is jsonData[i] = item or jsonData.push(item) (probably the first, though).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.