Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending to json file in javascript

I have a json file, employees.json, that I would like to append data to this object. The file looks like this:

var txt = '{"employees":[' +
'{"firstName":"Jerry","lastName":"Negrell","time":"9:15 am","email":"[email protected]","phone":"800-597-9405","image":"images/jerry.jpg" },' +
'{"firstName":"Ed","lastName":"Snide","time":"9:00 am","email":"[email protected]","phone":"800-597-9406","image":"images/ed.jpg" },' +
'{"firstName":"Pattabhi","lastName":"Nunn","time":"10:15 am","email":"[email protected]","phone":"800-597-9407","image":"images/pattabhi.jpg" }'+
']}';

I would like to append:

  • firstName:Mike
  • lastName:Rut
  • time:10:00 am
  • email:[email protected]
  • phone:800-888-8888
  • image:images/mike.jpg

to employee.json.

How would I accomplish this?

like image 665
Mike Avatar asked Sep 05 '12 22:09

Mike


People also ask

Can you append to a JSON file?

Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.

How do I append JSON data to existing JSON file in node JS?

Append file creates file if does not exist. But ,if you want to append JSON data first you read the data and after that you could overwrite that data. We have to read the data, parse, append, and then overwrite the original file because of the JSON format.

How do I add data to an existing JSON object?

Use push() method to add JSON object to existing JSON array in JavaScript. Just do it with proper array of objects .


2 Answers

var data = JSON.parse(txt);  //parse the JSON
data.employees.push({        //add the employee
    firstName:"Mike",
    lastName:"Rut",
    time:"10:00 am",
    email:"[email protected]",
    phone:"800-888-8888",
    image:"images/mike.jpg"
});
txt = JSON.stringify(data);  //reserialize to JSON
like image 200
Van Coding Avatar answered Sep 22 '22 17:09

Van Coding


JSON stands for Javascript object notation so this could simply be a javascript object

var obj = {employees:[
    {
      firstname:"jerry"
      ... and so on ...
     }
]};

When you want to add an object you can simply do:

object.employees.push({
   firstname: "Mike",
   lastName: "rut"
    ... and so on ....
});
like image 37
Ibu Avatar answered Sep 23 '22 17:09

Ibu