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:
to employee.json.
How would I accomplish this?
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.
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.
Use push() method to add JSON object to existing JSON array in JavaScript. Just do it with proper array of objects .
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
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 ....
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With