在javascript中附加到json文件

时间:2012-09-05 22:17:01

标签: javascript json

我有一个json文件employees.json,我想将数据附加到此对象。 该文件如下所示:

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

我想补充一下:

  • 姓:麦克
  • 名字:车辙
  • 时间:上午10:00
  • 电子邮件:rut@bah.com
  • 电话:800-888-8888
  • 图像:图像/ mike.jpg

到employee.json。

我将如何做到这一点?

2 个答案:

答案 0 :(得分:10)

var data = JSON.parse(txt);  //parse the JSON
data.employees.push({        //add the employee
    firstName:"Mike",
    lastName:"Rut",
    time:"10:00 am",
    email:"rut@bah.com",
    phone:"800-888-8888",
    image:"images/mike.jpg"
});
txt = JSON.stringify(data);  //reserialize to JSON

答案 1 :(得分:4)

JSON代表Javascript对象表示法,所以这可能只是一个javascript对象

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

如果要添加对象,只需执行以下操作:

object.employees.push({
   firstname: "Mike",
   lastName: "rut"
    ... and so on ....
});