Bongskie Bongskie - 4 months ago 13
JSON Question

How to replace old json object with a new one with NodeJS

How to replace old json object using NodeJS with a new updated object ?

Right now when i update the json file it saves the new data with the old one.

JSON :

[ {
"id": 1,
"name": "Sven",
"phone": "123123"
},
{
"id": 2,
"name": "Martin",
"phone": "2342342"
} ]


Here is my code :

var operation = POST.operation; // POST request comes with operation = update/insert/delete


if (operation == 'update') {
fs.readFile("file.json", "utf8", function (err, data) {

var jsonFileArr = [];
jsonFileArr = JSON.parse(data); //Parse the data from JSON file
var haveId = jsonFileArr.some(function (obj){ // Checks if the POST request have the same id as JSON file
return obj.id == POST.id;
})

if (haveId) { // if true

var updateData = []; // Array with POST data
updateData.push({
id: POST.id,
name: POST.name,
phone: POST.phone,
})
jsonFileArr.push(updateData);
var newUsers = JSON.stringify(jsonFileArr);
fs.writeFile("file.json", newUsers, "utf8");
console.log(err);
}
})
}


I should probably use
delete object
but how can i specify what object should be removed ?

So when i update data with id 1 it would delete the old id / Name / phone and write the new data.

Answer

My assumption base on your question is that you have multiple objects in one file. So the easy way to work around this would be to

      if (operation == 'update') {
        fs.readFile("file.json", "utf8", function (err, data) {

            var jsonFileArr = [];
            jsonFileArr = JSON.parse(data); //Parse the data from JSON file
            var haveId = jsonFileArr.some(function (obj){ // Checks if the POST request have the same id as JSON file
                return obj.id == POST.id;
            })

            if (haveId) {  // if true
                var updateData = []; // Array with POST data
                updateData.push({
                    id: POST.id,
                    name: POST.name,
                    phone: POST.phone,
                })

                for(let Arr of jsonFileArr){
                  if (Arr.id == POST.id){
                    let currentIndex = jsonFileArr.indexOf(Arr);
                    jsonFileArr.splice(currentIndex,1,updateData) //removing the old object and adding the new one
                  }
                }

                var newUsers = JSON.stringify(jsonFileArr);
                fs.writeFile("file.json", '', "utf8",function(err,res){  //Making the file empty
                  if(!err){
                    fs.writeFile("file.json", newUsers, "utf8",function(err,res){ //Writing the whole object back
                      if(err)console.log(err);
                      console.info(res);
                    });
                  }else{
                    console.log(err);
                  }
                });

            }
        })
    }
Comments