10

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?

1
  • 1
    Can you parse it into a JS object, add it, and then serialize it into JSON again? Commented Sep 5, 2012 at 22:19

2 Answers 2

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

2 Comments

i surround that in a js file with function add(){ .. } and called it in html with <form onsubmit="add()"><button>ADD</button></form> and didnt see the values added to the employees.json file
Yea, the code only overwrites the "txt" variable with the new JSON data. You'd have to save it to your file manually. If you are using node.js it would do this using fs.writeFile
5

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 ....
});

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.